https://www.cnblogs.com/jingxin1992/p/10579939.html
第一種:
[UIView animateWithDuration:3delay:3options:1animations:^{
? ? ? ? self.btn.transform = CGAffineTransformMakeTranslation(300,400);
? ? } completion:^(BOOL finished) {
? ? ? ? NSLog(@"view animation結(jié)束");
}];//不會(huì)阻塞線程太示,animations? block中的代碼對(duì)于是支持animation的代碼咐鹤,才會(huì)有延時(shí)效果慷垮,對(duì)于不支持animation的代碼 則 不會(huì)有延時(shí)效果
第二種:
[NSThread sleepForTimeInterval:3];//阻塞線程,浪費(fèi)性能 故硅,一般不推薦用。此方式在主線程和子線程中均可執(zhí)行秸抚。 建議放到子線程中勺届,以免卡住界面土居,沒(méi)有找到取消執(zhí)行的方法枣购。[self delayMethod];
第三種:最常用
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3* NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
});//定制了延時(shí)執(zhí)行的任務(wù)嬉探,不會(huì)阻塞線程,在主線程和子線程中都可以坷虑,效率較高(推薦使用)。此方式在可以在參數(shù)中選擇執(zhí)行的線程埂奈。 是一種非阻塞的執(zhí)行方式迄损, 沒(méi)有找到取消執(zhí)行的方法。
第四種:
[self performSelector:@selector(test) withObject:nil afterDelay:3];//此方式要求必須在主線程中執(zhí)行账磺,否則無(wú)效芹敌。 是一種非阻塞的執(zhí)行方式.[[selfclass] cancelPreviousPerformRequestsWithTarget:self];//取消本類(lèi)中執(zhí)行的performSelector:方法
第五種:定時(shí)器
1)NSTimer
[NSTimer scheduledTimerWithTimeInterval:3.0ftarget:self selector:@selector(delayMethod) userInfo:nil repeats:NO];//此方式要求必須在主線程中執(zhí)行,否則無(wú)效垮抗。 是一種非阻塞的執(zhí)行方式氏捞, 可以通過(guò)NSTimer類(lèi)的- (void)invalidate;取消執(zhí)行。
2)dispatch_source_t(比 NSTimer 更準(zhǔn)的定時(shí)器),也可以在子線程中執(zhí)行冒版,非阻塞執(zhí)行方式
dispatch_queue_t queue = dispatch_get_global_queue(0,0);
self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,0,0, queue);
? ? //開(kāi)始時(shí)間dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW,3.0* NSEC_PER_SEC);
? ? //間隔時(shí)間uint64_t interval =2.0* NSEC_PER_SEC;
dispatch_source_set_timer(self.timer, start, interval, 0);
? ? //設(shè)置回調(diào)dispatch_source_set_event_handler(self.timer, ^{
? ? [self delayMethod];
? ? dispatch_suspend(self.timer);
});
? ? //啟動(dòng)timerdispatch_resume(self.timer);