1. 程式人生 > >performSelector傳多個引數

performSelector傳多個引數

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);

 



作者:痴人會說夢
連結:https://www.jianshu.com/p/e676de277fbd
來源:簡書
簡書著作權歸作者所有,任何形式的轉載都請聯絡作者獲得授權並註明出處。

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);

 



作者:痴人會說夢
連結:https://www.jianshu.com/p/e676de277fbd
來源:簡書
簡書著作權歸作者所有,任何形式的轉載都請聯絡作者獲得授權並註明出處。