1. 程式人生 > >ios的延遲執行方法

ios的延遲執行方法

轉載源地址:http://poolo.iteye.com/blog/1820536 1.最直接的方法performSelector:withObject:afterDelay: 這種方法的缺點:每次要為延時寫一個方法 2.使用類別,用BOLCK執行

[程式碼]c#/cpp/oc程式碼:

01 @implementation NSObject (PerformBlockAfterDelay)
02
03 - (void)performBlock:(void (^)(void))block
04 afterDelay:(NSTimeInterval)delay
05 {
06 block = [[block copy] autorelease];
07 [self performSelector:@selector(fireBlockAfterDelay:)
08 withObject:block
09 afterDelay:delay];
10 }
11
12 - (void)fireBlockAfterDelay:(void (^)(void))block {
13 block();
14 }
15
16 @end
3.使用GCD

[程式碼]c#/cpp/oc程式碼:

1 void RunBlockAfterDelay(NSTimeInterval delay, void (^block)(void))
2 {
3 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC*delay),
4 dispatch_get_current_queue(), block);
5 }
poolo:注意 圖中的dispatch_getcurrent_queue() 方法在ios6已經被kill了 現在用dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH,0) 第一個引數是優先順序有,第二個引數為0或nil 如果要要對介面操作則使用dispatch_get_main_queue(); 參考:http://www.cnblogs.com/guwandong/archive/2012/08/08/2626211.html 4.可能是不太好的方法,用animation的completion引數

[程式碼]c#/cpp/oc程式碼:

1 [UIView animateWithDuration:0.0 delay:5.0 options:UIViewAnimationOptionAllowUserInteraction animations:^{
2 } completion:^(BOOL finished) {
3 //do stuff here
4 }];
5.使用NSOperationQueue,在應用程式的下一個主迴圈執行:

[程式碼]c#/cpp/oc程式碼:

1 [[NSOperationQueue mainQueue] addOperationWithBlock:aBlock];
這個和呼叫performSelector: with afterDelay of 0.0f等價