美文网首页ios 参考部分
performSelector传多个参数

performSelector传多个参数

作者: 痴人会说梦 | 来源:发表于2018-06-05 15:45 被阅读244次

    1.参数包装成字典
    2.自己实现对应方法 使用NSMethodSignure,NSInvoation

    - (id)performSelector:(SEL)aSelector
              withObjects:(NSArray *)arguments{
        
        //1.根据SEL实例化方法签名
        NSMethodSignature *signature = [[self class]instanceMethodSignatureForSelector:aSelector];
        //2.判断方法是否存在
        if (signature == nil) {
            //抛出异常
            NSLog(@"不存在这个方法");
            return nil;
        }
        //3.通过类方法实例化NSInvaction对象,设置target,selector
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
        [invocation setTarget:self];
        [invocation setSelector:aSelector];
        
        //获取参数的个数,默认方法都有 self,_cmd两个参数
        NSInteger signatureParmCount = signature.numberOfArguments - 2;
        NSInteger resultCount = MIN(signatureParmCount, arguments.count);
        
        //设置方法参数
        for (NSInteger i = 0; i < resultCount; i++) {
            id argument = arguments[i];
            if ([argument isKindOfClass:[NSNull class]]) continue;
            [invocation setArgument:&argument atIndex:i+2];
        }
        [invocation invoke];
        
        //返回值,获取返回值的长度,大于0表示有返回值
        id returnArgument = nil;
        if (signature.methodReturnLength) {
            [invocation getReturnValue:&returnArgument];
        }
        return returnArgument;
    }
    

    3.objc_msgsend

        NSString *str = @"字符串objc_msgSend";
        NSNumber *num = @20;
        NSArray *arr = @[@"数组值1", @"数组值2"];
        SEL sel = NSSelectorFromString(@"ObjcMsgSendWithString:withNum:withArray:");
        ((void (*) (id, SEL, NSString *, NSNumber *, NSArray *)) objc_msgSend) (self, sel, str, num, arr);
    

    相关文章

      网友评论

        本文标题:performSelector传多个参数

        本文链接:https://www.haomeiwen.com/subject/pwtmsftx.html