performSelector多参数

来源:互联网 发布:威纶通触摸屏编程手册 编辑:程序博客网 时间:2024/06/04 20:07

系统提供的performSelector最多只能传递两个参数,有的时候performSelector方法我们需要传递更多的参数,这个分类就能实现这个功能,仅供参考。

#import <Foundation/Foundation.h>@interface NSObject (PerformSelector)- (id)performSelector:(SEL)aSelector withObjects:(NSArray *)objects;@end
#import "NSObject+PerformSelector.h"@implementation NSObject (PerformSelector)- (id)performSelector:(SEL)aSelector withObjects:(NSArray *)objects{    //签名,一般包含了方法的名称/参数/返回值,签名一般用来设置参数和返回值的    NSMethodSignature *signature = [[self class] instanceMethodSignatureForSelector:aSelector];    //判断方法存不存在,不存在在此处理    if (!signature) {        //方法不存在,抛一个异常异常        NSString *exception = [NSString stringWithFormat:@"%@ can not be found", NSStringFromSelector(aSelector)];        [NSException raise:@"method not exit:" format:exception, nil];    }    //NSInvocation中保存了方法所属的对象/方法名称/参数/返回值    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];    invocation.target = self;    invocation.selector = aSelector;    //获取参数的数量:通过numberOfArguments获取的参数数量中包括了自带的self和_cmd    NSUInteger argCount = signature.numberOfArguments - 2;    //拿到给定数组的参数    NSUInteger arrCount = objects.count;    //按照这两个长度的最小的哪一个进行赋值    NSUInteger count = MIN(argCount, arrCount);    //变量数组    for (int i = 0; i < count; i++) {        id obj = objects[i];        if ([obj isKindOfClass:[NSNull class]]) {            obj = nil;        }        [invocation setArgument:&obj atIndex:i + 2];    }    //调用NSInvocation对象的invoke方法    [invocation invoke];    //获取方法的返回值    id result = nil;    if (signature.methodReturnLength != 0) {        [invocation getReturnValue:&result];    }    return result;}@end
1 0
原创粉丝点击