標籤:ext after delay nsdate efault 控制 patch 好用 sch
1,延時執行(不可重複)
[objc] view plain copy/** ** delay 不可重複 **/ - (void)timerMethodA { [self performSelector:@selector(methodAEvent) withObject:nil afterDelay:2.0f];//延時時間 } - (void)methodAEvent { NSLog(@"-- method_A"); }
效果我直接截取控制台的日誌了,就不做UI了。
2,用NSTimer執行定時和延時(可重複)
[objc] view plain copy/** ** 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"); } }
3,用dispatch_source_set_timer執行定時(可重複)
[objc] view plain copy/** ** 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執行延時(不可重複)
[objc] view plain copy/** ** 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
http://download.csdn.net/detail/xiongbaoxr/9417374
四個簡單易用的demo,關於iOS定時器和延時的,非常好用。