有時候,希望某段代碼,某個時間在一定時間後執行,這時候就要用到延遲執行。
常見的方法有以下幾種:
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
void RunBlockAfterDelay(NSTimeInterval delay, void (^block)(void)) { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC*delay), dispatch_get_current_queue(), block); }
[UIView animateWithDuration:0.0 delay:5.0 options:UIViewAnimationOptionAllowUserInteraction animations:^{ } completion:^(BOOL finished) { //do stuff here }];
1
[[NSOperationQueue
mainQueue] addOperationWithBlock:aBlock];
這個和調用performSelector: with afterDelay of 0.0f等價