iOS開發-順延強制

來源:互聯網
上載者:User

有時候,希望某段代碼,某個時間在一定時間後執行,這時候就要用到順延強制。

常見的方法有以下幾種:

1.最直接的方法performSelector:withObject:afterDelay:這種方法的缺點:每次要為延時寫一個方法

    [self performSelector:@selector(scale_2) withObject:nil afterDelay:0.5f];

-(void)scale_2{    UIImageView *round_2 = [[UIImageView alloc]initWithFrame:CGRectMake(105, 210, 20, 20)];    round_2.image = [UIImage imageNamed:@"round_"];    [splashView addSubview:round_2];    [self setAnimation:round_2];}

2.使用類別,用BOLCK執行
@implementation NSObject (PerformBlockAfterDelay)- (void)performBlock:(void (^)(void))block          afterDelay:(NSTimeInterval)delay{    block = [[block copy] autorelease];    [self performSelector:@selector(fireBlockAfterDelay:)               withObject:block               afterDelay:delay];}- (void)fireBlockAfterDelay:(void (^)(void))block {    block();}@end


3.使用GCD[代碼]c#/cpp/oc代碼:
void RunBlockAfterDelay(NSTimeInterval delay, void (^block)(void)){    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC*delay),      dispatch_get_current_queue(), block);}

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代碼:
[UIView animateWithDuration:0.0 delay:5.0 options:UIViewAnimationOptionAllowUserInteraction animations:^{} completion:^(BOOL finished) {    //do stuff here}];

5.使用NSOperationQueue,在應用程式的下一個主迴圈執行:[代碼]c#/cpp/oc代碼:
1 [[NSOperationQueue mainQueue] addOperationWithBlock:aBlock];
這個和調用performSelector: with afterDelay of 0.0f等價

學習的路上,與君共勉。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.