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
转载于:https://blog.51cto.com/bj007/538995
本文介绍了一种扩展NSObject的方法,使其支持通过Selector传递多个参数。通过对NSObject进行扩展,利用NSInvocation和NSMethodSignature,实现了performSelector方法能够接受参数数组的功能。
205

被折叠的 条评论
为什么被折叠?



