基础用法
performSelecor响应了OC语言的动态性:延迟到运行时才绑定方法。当我们在使用以下方法时:
[obj performSelector:@selector(play)]; [obj performSelector:@selector(play:) withObject:@"李周"]; [obj performSelector:@selector(play:with:) withObject:@"李周" withObject:@"谢华华"];
编译阶段并不会去检查方法是否有效存在,只会给出警告:
Undeclared selector ''
如果要执行的方法名也是动态不确定的一个参数:
[obj performSelector:selector];
编译器也只会提示说因为当前方法名未知可能会引起内存泄露相关问题:
PerformSelector may cause a leak because its selector is unknown
所以在实际开发中,为了避免运行时突然报错找不到方法等问题,少使用performSelector方法。
二 延迟执行
[obj performSelector:@selector(play) withObject:@"李周" afterDelay:4.f];
① 在子线程中执行会不会调用test方法
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_async(queue, ^{ [self performSelector:@selector(test) withObject:nil afterDelay:2]; });
会发现test方法并没有被调用,因为子线程中的runloop默认是没有启动的状态。使用run方法开启当前线程的runloop,但是一定要注意run方法和执行该延迟方法的顺序。
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_async(queue, ^{ [[NSRunLoop currentRunLoop] run]; [self performSelector:@selector(test) withObject:nil afterDelay:2]; });
会发现即便添加了run方法,但是test方法还是没有被调用,在最后打印当前线程的runloop,会发现:
timers =
{type = mutable-small, count = 1, values = ( 0 :
{valid = Yes, firing = No, interval = 0, tolerance = 0, next fire date = (1. @ 54), callout = (Delayed Perform) lZLearningFromInterviewController test (0x105ea0d9c / 0x104b2e2c0) (), context =
}
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]; });
此时test方法会被调用,分别打印执行完performSelecor和run方法之后,发现在执行完performSelector方法后该timer事件会被添加到子线程的runloop中:
timers =
{type = mutable-small, count = 1, values = ( 0 :
{valid = Yes, firing = No, interval = 0, tolerance = 0, next fire date = (1. @ 29), callout = (Delayed Perform) lZLearningFromInterviewController test (0x10e88fd9c / 0x1
但是当执行完run方法之后,runloop中的timer事件已经是执行完的状态:
timers =
{type = mutable-small, count = 0, values = ()},
所以在子线程中两者的顺序必须是先执行performSelector延迟方法之后再执行run方法。因为run方法只是尝试想要开启当前线程中的runloop,但是如果该线程中并没有任何事件(source、timer、observer)的话,并不会成功的开启。
② test方法中执行的线程
[self performSelector:@selector(test) withObject:nil afterDelay:2];
如果在子线程中调用该performSelector延迟方法,会发现调用该延迟方法的子线程和test方法中执行的子线程是同一个,也就是说:
对于该performSelector延迟方法而言,如果在主线程中调用,那么test方法也是在主线程中执行;如果是在子线程中调用,那么test也会在该子线程中执行。
这么想是错的,performSelector:withObject:只是一个单纯的消息发送,和时间没有一点关系,不需要runloop帮忙。所以不需要添加到子线程的Runloop中也能执行;根本原因是afterDelay方式调用需要timer,timer调用需要runloop。
三 异步执行
有时候面试关于多线程的问题时,会提问说:
如何在不使用GCD和NSOperation的情况下,实现异步线程?
反正我第一反应就是:幸亏,把NSThread给我留下了!

所以能直接使用NSThread的三个方法:
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(test) object:nil]; [NSThread detachNewThreadSelector:@selector(test) toTarget:self withObject:nil]; [NSThread detachNewThreadWithBlock:^{ NSLog(@"block中的线程 ---- %@",[NSThread currentThread]); }];
但是一般面试还会接着往下问:
如果也不使用NSThread已有的方法呢?
这个时候已经没有时间吐槽了只能接着想了…后来的后来我在perSelector的相关方法中找到了解答:
① performSelectorInBackground 后台执行
[self performSelectorInBackground:@selector(test) withObject:nil];
该方法一目了然,开启新的线程在后台执行test方法
②performSelector:onThread:在指定线程执行
[self performSelector:@selector(test) onThread:[NSThread currentThread] withObject:nil waitUntilDone:YES];
这个方法有一个thread参数是指定执行的线程,但是很奇怪当我使用自己创建的线程 [[NSThread alloc] init];时,并不会执行test方法,只有当使用[NSThread currentThread]时才会执行:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ [self performSelector:@selector(tests) onThread:[NSThread currentThread] withObject:nil waitUntilDone:NO]; });
还需要再考证考证这个方法的使用。
- (id)performSelector:(SEL)aSelector withObjects:(NSArray *)arguments{ //1.根据SEL实例化方法签名 NSMethodSignature *signature = [[self class]instanceMethodSignatureForSelector:aSelector]; //2.判断方法是否存在 if (signature == nil) { //抛出异常 NSLog(@"不存在这个方法"); return nil; } //3.通过类方法实例化NSInvaction对象,设置target,selector NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature]; [invocation setTarget:self]; [invocation setSelector:aSelector]; //获取参数的个数,默认方法都有 self,_cmd两个参数 NSInteger signatureParmCount = signature.numberOfArguments - 2; NSInteger resultCount = MIN(signatureParmCount, arguments.count); //设置方法参数 for (NSInteger i = 0; i < resultCount; i++) { id argument = arguments[i]; if ([argument isKindOfClass:[NSNull class]]) continue; [invocation setArgument:&argument atIndex:i+2]; } [invocation invoke]; //返回值,获取返回值的长度,大于0表示有返回值 id returnArgument = nil; if (signature.methodReturnLength) { [invocation getReturnValue:&returnArgument]; } return returnArgument; }
3.objc_msgsend
NSString *str = @"字符串objc_msgSend"; NSNumber *num = @20; NSArray *arr = @[@"数组值1", @"数组值2"]; SEL sel = NSSelectorFromString(@"ObjcMsgSendWithString:withNum:withArray:"); ((void (*) (id, SEL, NSString *, NSNumber *, NSArray *)) objc_msgSend) (self, sel, str, num, arr);
防止按钮多次点击
这种方式是在0.2秒内取消之前的点击事件,以做到防止多次点击。
-(void)completeClicked:(UIButton *)sender{ [[self class] cancelPreviousPerformRequestsWithTarget:self selector:@selector(buttonClick:) object:sender]; [self performSelector:@selector(buttonClick:) withObject:sender afterDelay:0.2f]; }
这种方式是在点击后设为不可被点击的状态,1秒后恢复
-(void)buttonClicked:(id)sender{ self.button.enabled =NO; [selfperformSelector:@selector(changeButtonStatus)withObject:nilafterDelay:1.0f];//防止重复点击 } -(void)changeButtonStatus{ self.button.enabled =YES; }
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/224189.html原文链接:https://javaforall.net
