1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| #import "GCMsgSend.h" #import <objc/message.h>
- (void)msgTest { //创建对象 GCMsgSend *msg = ( (GCMsgSend * (*)(id, SEL)) objc_msgSend) ((id)[GCMsgSend class],@selector(alloc)); //初始化对象 msg = ((GCMsgSend *(*)(id, SEL))objc_msgSend) ((id)msg, @selector(init)); //调用无参无返回值的方法 ((void (*)(id, SEL))objc_msgSend)((id)msg, @selector(noArgumentAndNoReturnValue)); //带参数不带无返回值 ((void(*)(id, SEL, NSString *))objc_msgSend)((id)msg, @selector(hasArguments:), @"一个参数,无返回值"); //不带参数有返回值 NSString *retValue = ((NSString *(*)(id, SEL))objc_msgSend)((id)msg, @selector(noArgumentsButRetuenValue)); NSLog(@"返回值是: %@", retValue); //带参数带返回值 int returnValue = ((int (*)(id, SEL, NSString *, int))objc_msgSend)((id)msg, @selector(hasArguments:andReturnValue:), @"参数1", 2018); NSLog(@"返回值是: %d", returnValue); //动态添加方法再调用 class_addMethod(msg.class, NSSelectorFromString(@"cStyleFunc"), (IMP)cStyleFunc, "v@:"); returnValue = ((int(*)(id, SEL, const void *, const void *))objc_msgSend)((id)msg, NSSelectorFromString(@"cStyleFunc"), "参数1", "参数2"); NSLog(@"返回值是: %d", returnValue); //带浮点返回值 float returnFloatValue = ((float(*)(id, SEL))objc_msgSend)((id)msg, @selector(noArgumentAndReturnFloatValue)); NSLog(@"浮点数返回值是: %f", returnFloatValue); //带结构体的返回值 objc_msgSend_stret 已经废弃 struct myStructTest structValue = ((struct myStructTest(*)(id, SEL))objc_msgSend)((id)msg, @selector(returnStructValue)); NSLog(@"结构体返回: name = %s, age = %d", structValue.name, structValue.age); //给父类发送消息 //初始化子类 GCMsgSendClass *msgClass = ((GCMsgSendClass *(*)(id, SEL))objc_msgSend)((id)[GCMsgSendClass class], @selector(alloc)); msgClass = ((GCMsgSendClass *(*)(id, SEL))objc_msgSend)((id)msgClass, @selector(init)); //给父类的方法发送消息 掉用objc_msgSendSuper 会Crash ((void(*)(id, SEL, NSString *))objc_msgSend)((id)msgClass, @selector(hasArguments:), @"子类调用父类的方法"); }
|