iOS开发-延迟执行

有时候,希望某段代码,某个时间在一定时间后执行,这时候就要用到延迟执行。

常见的方法有以下几种:

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等价


学习的路上,与君共勉。

你可能感兴趣的:(iOS开发-延迟执行)