使用 runtime 实现字符串转方法,并传递参数

利用runtime的动态机制实现字符串转方法并传递参数

使用 SEL 关键字引用方法声明,使用 methodForSelector 寻找方法实现,

使用函数指针调用方法。

 1 - (void)actionResponse:(NSString *)action withObject:(id)argument {
 2     
 3     SEL selector = NSSelectorFromString(action);
 4     if ([self respondsToSelector:selector]) {
 5         IMP imp = [self methodForSelector:selector];
 6         if (IsNilOrNull(argument)) {
 7             void (*func)(id, SEL) = (void *)imp;
 8             func(self, selector);
 9         } else {
10             void (*func)(id, SEL, id) = (void *)imp;
11             func(self, selector, argument);
12         }
13     }
14 }

 

posted @ 2018-09-17 13:51  CodeVector  阅读(708)  评论(0编辑  收藏  举报