1. 程式人生 > >iOS 中 延遲操作四種方式

iOS 中 延遲操作四種方式

spl close user scheduled gif lec nbsp 時間 time_t

本文列舉了四種延時執行某函數的方法及其一些區別。假如延時1秒時間執行下面的方法。

- (void)delayMethod { NSLog(@"execute"); }

1.performSelector方法

[self performSelector:@selector(delayMethod) withObject:nil afterDelay:1.0f];
此方式要求必須在主線程中執行,否則無效。是一種非阻塞的執行方式,暫時未找到取消執行的方法。

2.定時器:NSTimer

[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(delayMethod) userInfo:nil repeats:NO];
此方式要求必須在主線程中執行,否則無效。是一種非阻塞的執行方式,可以通過NSTimer類的- (void)invalidate;取消執行。

3. sleep方式

[NSThread sleepForTimeInterval:1.0f]; [self delayMethod];
此方式在主線程和子線程中均可執行。是一種阻塞的執行方式,建義放到子線程中,以免卡住界面沒有找到取消執行的方法。

4.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]; });
此方式在可以在參數中選擇執行的線程。是一種非阻塞的執行方式,沒有找到取消執行的方法。
技術分享圖片
1.    延時方法一(使用NSRunLoop類中的方法實現延遲執行,,常用,,performSelector必須在主線程中執行)

     [self delayOne];

    

 
2. 延時方法二(GCD方式常用)(此方式在可以在參數中選擇執行的線程。是一種非阻塞的執行方式) __block ViewController* bself = self; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [bself isOneway]; }); 3. 延時方法三(必須在主線程中執行) NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:5.0f target:self selector:@selector(isOneway) userInfo:nil repeats:NO]; 取消方法 [timer invalidate]; 4. 延時方法四 (此方式在主線程和子線程中均可執行,是一種阻塞的執行方式,建議放到子線程中,以免卡住界面) [NSThread sleepForTimeInterval:5.0]; [self isOneway]; -(void)delayOne{ [self performSelector:@selector(isOneway) withObject:nil afterDelay:5.0f]; } -(void)isOneway{ self.view.backgroundColor = [UIColor cyanColor]; }
View Code

iOS 中 延遲操作四種方式