- (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay;
--1--
知识点:这个方法是单线程的,也就是说只有当前调用此方法的函数执行完毕后,selector方法才会被调用。
- (void)mainMethod { [self performSelector:@selector(delayMethod) withObject:nil afterDelay:1]; NSLog(@"调用方法==开始"); sleep(5); NSLog(@"调用方法==结束"); } - (void)delayMethod { NSLog(@"执行延迟方法"); } 执行结果(注意log打印的顺序): 调用方法==开始 调用方法==结束 执行延迟方法
实战经验:正因为本方法是一个单线程的,所以有些时候,我们会遇到虽然调用了这个方法,但是不执行的问题。这时,我们需要将原代码改造如下:
改造前代码:无法执行延迟方法
-(void)someMethod { [self performSelector:@selector(labelDidDisappeared:) withObject:label afterDelay:2]; //因为某些原因,不被调用,没有执行 } -(void)labelDidDisappeared:(UILabel *)label { [label removeFromSuperview]; [label release]; }
改造后代码: 可以正常执行延迟方法
-(void)someMethod { //关键 [self performSelectorOnMainThread:@selector(labelWillDisappeared:) withObject:label waitUntilDone:NO]; } -(void)labelWillDisappeared:(UILabel *)label { [self performSelector:@selector(labelDidDisappeared:) withObject:label afterDelay:2]; } -(void)labelDidDisappeared:(UILabel *)label { [label removeFromSuperview]; [label release]; }
知识扩展:以下两个方法均是多线程方法
- (void)performSelectorInBackground:(SEL)aSelector withObject:(id)arg
和
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait;
参考:http://blog.csdn.net/baxiaxx/article/details/7878338 感谢原作者的无私和奉献!
--2--
知识点:该方法只能接受一个参数。如果需要传递多个参数怎么办呢? 让selector调用的方法接受的参数类型修改为Dictionary类型。
注意:
(1)如果调用的selector不接受参数则,withObject:nil
(2) 通过performSelector:withObjcet:afterDelay调用的方法不能有返回值
知识扩展:performSelector 带多个参数
//第一个试验:带一个参数
- (void) fooOneIput:(NSString*) first {
NSLog(@"Logs %@", first);
}
//然后调用它
[self performSelector:@selector(fooOneInput:) withObject:@"first"];
//第二个试验:带多个参数
- (void) fooFirstInput:(NSString*) first secondInput:(NSString*) second {
NSLog(@"Logs %@ then %@", first, second);
}
//然后调用它
[self performSelector:@selector(fooFirstInput:secondInput:) withObject:@"first" withObject:@"second"];
实战经验:经实验,只有performSelector: withObject: 方法可以带多个参数,其它类似的perform方法均不行,包括和此方法最类似的performSelectorInBackground:withObject: 方法。
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait;
代码如下:
- (void)changeText:(NSString *)string
{
label.text = string;
NSLog(@"changeText:(NSString *)string");
}
- (void)changePopoverSize
{
[self performSelectorOnMainThread:@selector(changeText:) withObject:@"Happy aha111" waitUntilDone:YES];
NSLog(@"changePopoverSize#####end");
sleep(5);
NSLog(@"changePopoverSize-----end");
}
执行结果如下:
2012-08-17 17:19:29.618 awrbv[2024:f803] changeText:(NSString *)string
2012-08-17 17:19:29.619 awrbv[2024:f803] changePopoverSize#####end
2012-08-17 17:19:34.620 awrbv[2024:f803] changePopoverSize-----end
可以看出,如果waitUntilDone:YES那么等changeText执行完毕后再往下执行
如果waitUntilDone:NO的话,结果如下:
2012-08-17 17:21:12.135 awrbv[2049:f803] changePopoverSize#####end
2012-08-17 17:21:17.137 awrbv[2049:f803] changePopoverSize-----end
2012-08-17 17:21:17.139 awrbv[2049:f803] changeText:(NSString *)string