iOS 方法調(diào)用的幾種方法

原文鏈接

示例方法

- (void)printStr:(NSString*)str{
    NSLog(@"printStr  %@",str);
}
1. 直接調(diào)用
[self printStr:@"hello world 1"];
2. performSelector
[self performSelector:@selector(printStr:) withObject:@"hello world 2"];
3.NSMethodSignature & NSInvocation
- (id)performSelector:(SEL)selector byDelegate:(id<EWLiveMessageProcessorDelegate>) delegate withObjects:(NSArray *)objects
{
    #方法簽名(方法的描述)
    NSMethodSignature *signature = [[delegate class] instanceMethodSignatureForSelector:selector];
    if (signature == nil) {
        
        #可以拋出異常也可以不操作。
        return nil;
    }
    
   # NSInvocation : 利用一個(gè)NSInvocation對(duì)象包裝一次方法調(diào)用(方法調(diào)用者、方法名、方法參數(shù)、方法返回值)
    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
    invocation.target = delegate;
    invocation.selector = selector;
    
    #設(shè)置參數(shù)
    NSInteger paramsCount = signature.numberOfArguments - 2; // 除self、_cmd以外的參數(shù)個(gè)數(shù)
    paramsCount = MIN(paramsCount, objects.count);
    for (NSInteger i = 0; i < paramsCount; i++) {
        id object = objects[i];
        if ([object isKindOfClass:[NSNull class]]) continue;
        [invocation setArgument:&object atIndex:i + 2];
    }
    
    # 調(diào)用方法
    [invocation invoke];
    
    #獲取返回值
    id returnValue = nil;
    if (signature.methodReturnLength) { // 有返回值類型,才去獲得返回值
        [invocation getReturnValue:&returnValue];
    }
    
    return returnValue;
}

4. objc_msgSend
SEL sel = NSSelectorFromString(@"printWithString:withNum:withArray:");

#帶參數(shù)無(wú)返回值
((void (*) (id, SEL, NSString *, NSNumber *, NSArray *)) objc_msgSend) (self, sel, str, num, arr);

#帶參數(shù)及返回值
((int (*)(id, SEL, NSString *, int))objc_msgSend)( (id)msg,
                               @selector(hasArguments:andReturnValue:),
                               @"參數(shù)1",
                               2016);

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容