iPhone How-to:多参数selector

    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;
    }
}
@end

你可能感兴趣的:(移动开发,职场,多参数,selector,休闲)