[ios]关于objc_msgSend的学习

最近项目需要,使用了objc-c的runtime的objc_msgSend函数。


首先要引入头文件:

#import

#import


平时我们调用一个函数如下:

-(void)test{

NSLog(@"test");

会使用如下:

[self test];

换成runtime时,如下:

objc_msgSend(self, @selector(test));


当有多个参数时,如:

-(void)test:(NSString *)arg1  arg2:(NSString *)arg2{

}

如下:

[self test:arg1 arg2:arg2];

objc_msgSend(self, @selector(test), arg1, arg2);

或者(因为selector找不到对应的方法,所以要用下面这种):

SEL testFunc = NSSelectorFromString(@"test:arg2:");

objc_msgSend(self, testFunc, arg1, arg2);



最近在ios8时,发现如下报错:

Too many arguments to function call, expected 0, have 3


解决方法:

((void(*)(id,SEL, id,id))objc_msgSend)(self, testFunc, arg1, arg2);



你可能感兴趣的:([ios]关于objc_msgSend的学习)