各种延时操作

各种延时操作

延时执行方法(可以取消执行)

// 5s后执行某方法
NSString *toDoStr = @"play";
NSString *toDoStr2 = @"play02";

// 如果已经 perform 但还没执行,取消上次 perform,并重新计时
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(toDoMethod:) object:toDoStr]; 
[self performSelector:@selector(toDoMethod:) withObject:toDoStr afterDelay:5]; // 5s 后使用 toDoStr 调用 toDoMethod 方法


// 如果已经 perform 但还没执行,取消上次 perform,使用 toDoStr2 调用,并重新计时
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(toDoMethod:) object:toDoStr]; // 若使用 toDoStr 调用 toDoMethod 方法还没执行(还在5s内)则取消执行
[self performSelector:@selector(toDoMethod:) withObject:toDoStr2 afterDelay:5]; // 5s 后使用 toDoStr2 调用 toDoMethod 方法

执行动画,延时执行,执行一定时间后延时取消

// delay:3, 3s 后执行动画
// UIViewAnimationOptionAutoreverse 动画运行到结束点后仍然以动画方式回到初始点
// [UIView setAnimationRepeatCount:10]; 重复10次
// animateWithDuration:0.5 每次动画执行 0.5s (共执行 0.5 * 10 s 后,执行completion)
//
UIImageView *show = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"showPic"]];
[self.contentView addSubview:show];
self.show = show;
show.frame = CGRectMake(90, 100, 50, 50);

[UIView animateWithDuration:0.5
                      delay:3
                    options:UIViewAnimationOptionAutoreverse animations:^{
    [UIView setAnimationRepeatCount:10];
    show.frame = CGRectMake(100, 100, 50, 50);
} completion:^(BOOL finished) {
    [show removeFromSuperview];
    self.show = nil;
}];

dispatch方法

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 2*NSEC_PER_SEC), dispatch_get_main_queue(), ^{
    // do something in main queue
});


//在主线程延迟执行  
 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
   [self delayDo:@"GCD"];
   });
   
//在子线程延迟执行
   dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
   [self delayDo:@"Global-GCD"];
   });

NSTimer 方法

NSDate *scheduledTime = [NSDate dateWithTimeIntervalSinceNow:10.0]; //设置开始执行的时间为:从现在开始计时,10s后
NSString *customUserObject = @"To demo userInfo";
NSTimer *timer = [[NSTimer alloc] initWithFireDate:scheduledTime
                                          interval:2
                                            target:self
                                          selector:@selector(task:)
                                          userInfo:customUserObject
                                           repeats:YES];
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
[runLoop addTimer:timer forMode:NSDefaultRunLoopMode];


- (void)task:(id)sender{
    NSTimer *localTimer = (NSTimer *)sender;
    NSLog(@"Schedule task has executed with this user info: %@", [localTimer userInfo]);
}

参考链接