四个简单易用的demo,关于iOS定时器和延时的,非常好用。
1,延时执行(不可重复)
/**
** delay 不可重复
**/
- (void)timerMethodA
{
[self performSelector:@selector(methodAEvent)
withObject:nil
afterDelay:2.0f];//延时时间
}
- (void)methodAEvent
{
NSLog(@"-- method_A");
}
效果我直接截取控制台的日志了,就不做UI了。
2,用NSTimer执行定时和延时(可重复)
/**
** timer 可重复
**/
- (void)timerMethodB
{
_timer = [NSTimer scheduledTimerWithTimeInterval:1.0f //间隔时间
target:self
selector:@selector(methodBEvnet)
userInfo:nil
repeats:YES];
}
- (void)methodBEvnet
{
count++;
NSLog(@"-- Method_B count: %d", count);
if (count >= 5) {
[_timer invalidate]; //重复5次,timer停止
NSLog(@"-- end");
}
}
/**
** dispatch_time 可重复
**/
- (void)timerMethodC
{
__block int i = 0;
CGFloat duration = 1.0f; //间隔时间
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, duration * NSEC_PER_SEC, 0);
dispatch_source_set_event_handler(timer, ^{
i++;
if (i > 5) {
dispatch_source_cancel(timer); //执行5次后停止
NSLog(@"-- end");
}else{
NSLog(@"-- Method_C i:%d", i);
}
});
dispatch_resume(timer);
}
4,用dispatch_after执行延时(不可重复)
/**
** dispatch_time 不可重复
**/
- (void)timerMethodD
{
CGFloat delayTime = 2.0f; //延时时间
dispatch_time_t timer = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayTime *NSEC_PER_SEC));
dispatch_after(timer, dispatch_get_main_queue(), ^{
NSLog(@"-- Method_D time:%@", [NSDate date]);
});
}
文章最后奉上demo