使用performSelector做消息分发

一、应用场景
1、performSelector是运行时系统负责去找方法的,在编译时候不做任何校验;如果直接调用编译是会自动校验。Cocoa支持在运行时向某个类添加方法,即方法编译时不存在,但是运行时候存在,这时候必然需要使用performSelector去调用。所以有时候如果使用了performSelector,为了程序的健壮性,会使用检查方法- (BOOL)respondsToSelector:(SEL)aSelector;
2、直接调用方法时候,一定要在头文件中声明该方法的使用,也要将头文件import进来。而使用performSelector时候,可以不用import头文件包含方法的对象,直接用performSelector调用即可。
3、需要在pod库a里面调用另外一个pod库b中的方法

二 延迟执行使用
[obj performSelector:@selector(play) withObject:@“李周” afterDelay:4.f];
当然Runloop为了节省资源并不会在准确的时间点触发事件。
而performSelector:withObject:afterDelay:其实就是在内部创建了一个NSTimer,然后会添加到当前线程的Runloop中。所以当该方法添加到子线程中时,需要格外的注意两个地方:1.会发现方法并没有被调用,因为子线程中的runloop默认是没有启动的状态。2.子线程中两者的顺序必须是先执行performSelector延迟方法之后再执行run方法。
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
[self performSelector:@selector(test) withObject:nil afterDelay:2];
[[NSRunLoop currentRunLoop] run];
});

三、 多参传递
以NSArray的形式传值,然后创建NSInvocation的方式,将参数一一绑定。
-(id)performSelector:(SEL)aSelector withObject:(NSArray *)object
{
//获得方法签名
NSMethodSignature *signature = [[self class] instanceMethodSignatureForSelector:aSelector];

if (signature == nil) {
    return nil;
}

//使用NSInvocation进行参数的封装
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
invocation.target = self;
invocation.selector = aSelector;

//减去 self _cmd
NSInteger paramtersCount = signature.numberOfArguments - 2;
paramtersCount = MIN(object.count, paramtersCount); 

for (int i = 0; i < paramtersCount; i++) {
    id obj = object[i];
    
    if ([obj isKindOfClass:[NSNull class]]) continue;
    [invocation setArgument:&obj atIndex:i+2];
}

[invocation invoke];

id returnValue = nil;
if (signature.methodReturnLength > 0) { //如果有返回值的话,才需要去获得返回值
    [invocation getReturnValue:&returnValue];
}

return returnValue;

}
///////////////////////////////////////////////////
NSNumber *age = [NSNumber numberWithInt:20];
NSString *name = @“zcp”;
NSString *gender = @“男”;
NSArray *friends = @[@“1”,@“2”];
SEL selector = NSSelectorFromString(@“getAge:name:gender:friends:”);
NSArray *array = @[age,name,gender,friends];
[self performSelector:selector withObject:array];

猜你喜欢

转载自blog.csdn.net/iOS_ZCP/article/details/89400729