多参selector
本文出自 “林家男孩” 博客,请务必保留此出处http://bj007.blog.51cto.com/1701577/538995
1 Selector是Objective-C一个非常强大的特性,合理使用Selector可以大大简化实现并避免重复代码。但NSObject提供 的performSelector最多只支持两个参数,对于两个以上的参数就无能为力了。一番调查后针对NSObject增加了如下扩展,使得 performSelector可以支持传入参数数组。多个参数就不再是问题了。
2 @interface NSObject (Addition)
3
4 - (id)performSelector:(SEL)selector withObjects:(NSArray *)objects;
5
6 @end
7
8 @implementation NSObject (Addition)
9
10 - (id)performSelector:(SEL)selector withObjects:(NSArray *)objects {
11 NSMethodSignature *signature = [self methodSignatureForSelector:selector];
12 if (signature) {
13 NSInvocation* invocation = [NSInvocation invocationWithMethodSignature:signature];
14 [invocation setTarget:self];
15 [invocation setSelector:selector];
16 for(int i = 0; i < [objects count]; i++){
17 id object = [objects objectAtIndex:i];
18 [invocation setArgument:&object atIndex: (i + 2)];
19 }
20 [invocation invoke];
21 if (signature.methodReturnLength) {
22 id anObject;
23 [invocation getReturnValue:&anObject];
24 return anObject;
25 } else {
26 return nil;
27 }
28 } else {
29 return nil;
30 }
31 }
32 @end
然后再膜拜辉哥