iOS 方法调用的几种方法

原文链接

示例方法

- (void)printStr:(NSString*)str{
    NSLog(@"printStr  %@",str);
}
1. 直接调用
[self printStr:@"hello world 1"];
2. performSelector
[self performSelector:@selector(printStr:) withObject:@"hello world 2"];
3.NSMethodSignature & NSInvocation
- (id)performSelector:(SEL)selector byDelegate:(id) delegate withObjects:(NSArray *)objects
{
    #方法签名(方法的描述)
    NSMethodSignature *signature = [[delegate class] instanceMethodSignatureForSelector:selector];
    if (signature == nil) {
        
        #可以抛出异常也可以不操作。
        return nil;
    }
    
   # NSInvocation : 利用一个NSInvocation对象包装一次方法调用(方法调用者、方法名、方法参数、方法返回值)
    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
    invocation.target = delegate;
    invocation.selector = selector;
    
    #设置参数
    NSInteger paramsCount = signature.numberOfArguments - 2; // 除self、_cmd以外的参数个数
    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];
    }
    
    # 调用方法
    [invocation invoke];
    
    #获取返回值
    id returnValue = nil;
    if (signature.methodReturnLength) { // 有返回值类型,才去获得返回值
        [invocation getReturnValue:&returnValue];
    }
    
    return returnValue;
}

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

#带参数无返回值
((void (*) (id, SEL, NSString *, NSNumber *, NSArray *)) objc_msgSend) (self, sel, str, num, arr);

#带参数及返回值
((int (*)(id, SEL, NSString *, int))objc_msgSend)( (id)msg,
                               @selector(hasArguments:andReturnValue:),
                               @"参数1",
                               2016);

你可能感兴趣的:(iOS 方法调用的几种方法)