iOS-调用方法

在 iOS中可以直接调用某个对象的消息方式有两种:

利用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;
if ([self canPerformAction:@selector(myLog:) withSender:nil]) {
    [self performSelector:@selector(p_Log:) withObject:@"abc" afterDelay:5];
}

- (void)p_Log:(NSString*)log{
     NSLog(@"MyLog = %@",log);
  }
NSInvocation使用方法
    NSString *str1 = @"a";
    NSString *str2 = @"b";
    NSString *str3 = @"c";
    
    NSMethodSignature *sign = [self methodSignatureForSelector:@selector(personInfo:age:gender:)];
    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:sign];
    [invocation setTarget:self];
    [invocation setSelector:@selector(personInfo:age:gender:)];
    [invocation setArgument:&str1 atIndex:2];
    [invocation setArgument:&str2 atIndex:3];
    [invocation setArgument:&str3 atIndex:4];
    [invocation invoke];


- (void)personInfo:(NSString *)strName age:(NSString *)strAge gender:(NSString *)strGender {
    NSLog(@"%@,%@,%@",strName,strAge,strGender);
}

一开始以为setArgument 的index 从0开始代表第一个参数,结果崩溃了,po了一下发现

Printing description of invocation:

return value: {v} void
target: {@} 0x0
selector: {:} null
argument 2: {@} 0x0
argument 3: {@} 0x0
argument 4: {@} 0x0
+ (nullable NSMethodSignature *)signatureWithObjCTypes:(const char *)types;

从这个方法可以看的出来的types是char类型的 personInfo这个方法其实就是"v@:@@@"。

这里的Index要从2开始,以为0跟1已经被占据了,分别是self(target),selector(_cmd)

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