Selector Perform 扩展 多参

来源:互联网 发布:麦克风调音软件 编辑:程序博客网 时间:2024/06/03 23:09


http://hi.baidu.com/ncudlz/item/f074c04b353d4fd0c1a592eb

Selector是Objective-C一个非常强大的特性,合理使用Selector可以大大简化实现并避免重复代码。但NSObject提供  的performSelector最多只支持两个参数, 

对于两个以上的参数就没有能力为力了。一番调查后针对NSObject增加了如下扩展,使得 performSelector可以支持传入参数数组。多个参数就不再是问题了。   
@interface NSObject (Addition) 
- (id)performSelector:(SEL)selector withObjects:(NSArray *)objects; 
@end 
@implementation NSObject (Addition) 
- (id)performSelector:(SEL)selector withObjects:(NSArray *)objects {  
      NSMethodSignature *signature = [self methodSignatureForSelector:selector];  
      if (signature) {  
          NSInvocation* invocation = [NSInvocation invocationWithMethodSignature:signature];  
          [invocation setTarget:self];  
          [invocation setSelector:selector];  
          for(int i = 0; i < [objects count]; i++){  
              id object = [objects objectAtIndex:i];  
              [invocation setArgument:&object atIndex: (i + 2)];         
          }  
          [invocation invoke];  
          if (signature.methodReturnLength) {  
              id anObject;  
              [invocation getReturnValue:&anObject];  
              return anObject;  
          } else {  
              return nil;  
          }  
      } else {  
          return nil;  
      }  
  }  
原创粉丝点击