调用方法的两种方式

2018-09-07  本文已影响0人  Scott_Dove

利用performSelector 和NSInvocation来调用

相同点:父类都是NSObject不同点:performSelector最多传两个参数,使用比较简单

performSelector的方法以及部分使用方法


- (id)performSelector:(SEL)aSelector;

- (id)performSelector:(SEL)aSelector withObject:(id)object;

- (id)performSelector:(SEL)aSelector withObject:(id)object1 withObject:(id)object2;

NSInvocation使用方法

    NSString *name = @"scott";
    NSString *age = @"26";
    NSString *sex = @"男";
    NSMethodSignature *signture = [self methodSignatureForSelector:@selector(name:age:sex:)];
    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signture];
    [invocation setTarget:self];
    [invocation setSelector:@selector(name:age:sex:)];
    [invocation setArgument:&name atIndex:1];
    [invocation setArgument:&age atIndex:2];
    [invocation setArgument:&sex atIndex:3];
    [invocation invoke];
 
 
- (void)name:(NSString *)name age:(NSString *)age sex:(NSString *)sex{
    NSLog(@"姓名:%@ 年龄 %@ 性别 %@",name,age,sex);
}

这里需要注意的是setArgument的index 我们的参数需要从2开始,1 2分别被self(target),selector(_cmd)占据了

上一篇 下一篇

猜你喜欢

热点阅读