美文网首页
iOS方法调用总结

iOS方法调用总结

作者: WQDev | 来源:发表于2022-02-10 16:23 被阅读0次

    1.直接调用

    - (void)callFunc1 {
        ViewController *someObj = [ViewController new];
        [someObj foo:@"1"];
    }
    

    2.performSelector

    - (void)callFunc2 {
        ViewController *someObj = [ViewController new];
        [someObj performSelector:@selector(foo:) withObject:@"2"];
    }
    
    1. NSInvocation
    - (void)callFunc3 {
        ViewController *someObj = [ViewController new];
        //获取方法签名
        NSMethodSignature *signature = [self methodSignatureForSelector:@selector(foo:)];
        //获取方法签名对应的invocation
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
        //设置消息接受者,与[invocation setArgument:(__bridge void * _Nonnull)(self) atIndex:0]等价
        [invocation setTarget:someObj];
        //设置要执行的selector。与[invocation setArgument:@selector(foo:) atIndex:1] 等价
        [invocation setSelector:@selector(foo:)];
        //设置参数
        NSString *str = @"3";
        [invocation setArgument:&str atIndex:2];
        //开始执行
        [invocation invoke];
    }
    
    1. NSInvocationOperation
    - (void)callFunc4 {
        ViewController *someObj = [ViewController new];
        NSInvocationOperation *invocationOp = [[NSInvocationOperation alloc] initWithTarget:someObj selector:@selector(foo:) object:nil];
        NSString *str = @"4";
        [invocationOp.invocation setArgument:&str atIndex:2];
        [invocationOp start];
    //    NSInteger ret = 0;
    //    [invocationOp.result getValue:&ret]; //获取返回值要调用这个方法
    }
    

    5.objc_msgSend函数指针

    - (void)callFunc5 {
        ViewController *someObj = [ViewController new];
        SEL selector = NSSelectorFromString(@"foo:");
        IMP imp = [someObj methodForSelector:selector];
        void (*msgSendPointer)(id, SEL, NSString*) = (void *)imp;
        msgSendPointer(someObj, selector, @"5");
    }
    

    ViewController的foo方法

    - (void)foo:(NSString*)value {
        NSArray *syms = [NSThread  callStackSymbols];
        if ([syms count] > 1) {
            NSLog(@"foo=%@=== %@ ", value,[syms objectAtIndex:1]);
        }
    }
    

    相关文章

      网友评论

          本文标题:iOS方法调用总结

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