有三个办法:
-
[NSThread sleepForTimeInterval:];
但是这个方法并不好,因为它就是相当于睡眠了给定的时间不走了,所以会卡住当前线程。 -
performSelector:withObject:afterDelay:
这个方法直接在主线程中操作,但是不会卡住线程,程序依次执行,等过了指定延迟时间再回来执行相应操作。 -
double delayInSeconds = 2.0;
dispatch_queue_t mainQueue = dispatch_get_main_queue();
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW,delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, mainQueue, ^{
NSLog(@"延时执行的2秒");
});
也不会卡住线程,如果queue是主线程,则操作会在主线程中执行,如果queue是global队列,则会开个子线程