PerformSelecter
當調(diào)用 NSObject 的 performSelecter:afterDelay: 后包归,實際上其內(nèi)部會創(chuàng)建一個 Timer 并添加到當前線程的 RunLoop 中回怜。所以如果當前線程沒有 RunLoop翘紊,則這個方法會失效。
當調(diào)用 performSelector:onThread: 時暮刃,實際上其會創(chuàng)建一個 Timer 加到對應的線程去跨算,同樣的,如果對應線程沒有 RunLoop 該方法也會失效椭懊。
其他的performSelector系列方法是類似的
直接上代碼
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self tryPerformSelectorOnMianThread];
__weak typeof(self) weakSelf = self;
//backGroundThread并不會被調(diào)用到,這是因為诸蚕,在調(diào)用performSelector:onThread: withObject: waitUntilDone的時候,系統(tǒng)會給我們創(chuàng)建一個Timer的source氧猬,加到對應的RunLoop上去背犯,然而這個時候我們沒有RunLoop
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[weakSelf tryPerformSelectorOnbackGroundThread1];
});
//在tryPerformSelectorOnbackGroundThread1上我們添加個RunLoop,此時backGroundThread2就可以被調(diào)用到
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[weakSelf tryPerformSelectorOnbackGroundThread2];
});
//那么為什么主線程中的perfom selector卻能夠正常調(diào)用呢?通過上面的例子相信你已經(jīng)猜到了盅抚,主線程的RunLoop是一直存在的漠魏,所以我們在主線程中執(zhí)行的時候,無需再添加RunLoop妄均。
//小結(jié):當perform selector在后臺線程中執(zhí)行的時候柱锹,這個線程必須有一個開啟的runLoop
}
- (void)tryPerformSelectorOnMianThread{
[self performSelector:@selector(mainThreadMethod) withObject:nil];
}
- (void)tryPerformSelectorOnbackGroundThread1{
//backGroundThread并不會被調(diào)用到,這是因為哪自,在調(diào)用performSelector:onThread: withObject: waitUntilDone的時候,系統(tǒng)會給我們創(chuàng)建一個Timer的source禁熏,加到對應的RunLoop上去壤巷,然而這個時候我們沒有RunLoop
[self performSelector:@selector(backGroundThread1) onThread:[NSThread currentThread] withObject:nil waitUntilDone:NO];
//默認是會在MainRunLoop中去執(zhí)行,故他可以調(diào)用到backGroundThread
// [self performSelector:@selector(backGroundThread1) withObject:nil];
[self tryPerformSelectorOnbackGroundThread2];
}
- (void)tryPerformSelectorOnbackGroundThread2{
//在tryPerformSelectorOnbackGroundThread1上我們添加個RunLoop,此時backGroundThread2就可以被調(diào)用到
[self performSelector:@selector(backGroundThread2) onThread:[NSThread currentThread] withObject:nil waitUntilDone:NO];
[[NSRunLoop currentRunLoop] run];
}
- (void)mainThreadMethod{
NSLog(@"execute %s",__func__);
}
- (void)backGroundThread1{
NSLog(@"currentThread:%@",[NSThread currentThread]);
NSLog(@"backGroundThread1 --> execute %s",__FUNCTION__);
}
- (void)backGroundThread2{
NSLog(@"currentThread:%@",[NSThread currentThread]);
NSLog(@"backGroundThread2 --> execute %s",__FUNCTION__);
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者