本文轉(zhuǎn)載自http://blog.csdn.net/chenyong05314/article/details/24695897
本文列舉了四種延時執(zhí)行某函數(shù)的方法及其一些區(qū)別。假如延時1秒時間執(zhí)行下面的方法。
- (void)delayMethod { NSLog(@"execute"); }
performSelector方法[self performSelector:@selector(delayMethod)  withObject:nil afterDelay:1.0f]; 此方式要求必須在主線程中執(zhí)行,否則無效。 是一種非阻塞的執(zhí)行方式,  暫時未找到取消執(zhí)行的方法。
定時器:NSTimer [NSTimer scheduledTimerWithTimeInterval:1.0f    target:self selector:@selector(delayMethod) userInfo:nil    repeats:NO]; 此方式要求必須在主線程中執(zhí)行,否則無效。 是一種非阻塞的執(zhí)行方式, 可以通過NSTimer類的- (void)invalidate;取消執(zhí)行。
sleep方式 [NSThread sleepForTimeInterval:1.0f]; [self delayMethod];        此方式在主線程和子線程中均可執(zhí)行。 是一種阻塞的執(zhí)行方式,建方放到子線程中,以免卡住界面 沒有找到取消執(zhí)行的方法。
GCD方式 double delayInSeconds = 1.0;   __block ViewController* bself    = self;   dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC)); dispatch_after(popTime, dispatch_get_main_queue(), ^(void){   [bself delayMethod]; }); 此方式在可以在參數(shù)中選擇執(zhí)行的線程。 是一種非阻塞的執(zhí)行方式, 沒有找到取消執(zhí)行的方法。
新聞熱點
疑難解答