第一种,方法不带参数时使用
注:此方法是一种非阻塞的执行方式,未找到取消执行的方法。
[self performSelector:@selector(delayMethod) withObject:nil/*可传任意类型参数*/ afterDelay:2.0];
第二种,GCD方式
注:此方法可以在参数中选择执行的线程,是一种非阻塞执行方式。没有找到取消执行方式。
__block ViewController weakSelf = self;
dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC));
dispatch_after(delayTime, dispatch_get_main_queue(), ^{
[weakSelf delayMethod];
});
第三种
[UIView animateWithDuration:0 delay:2.0 options:UIViewAnimationOptionAllowUserInteraction animations:^{
} completion:^(BOOL finished) {
[self delayMethod];
}];
第四种
注:此方法是一种非阻塞的执行方式,
取消执行方法:- (void)invalidate;
即可
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(delayMethod) userInfo:nil repeats:NO];
第五种
此方法是一种阻塞执行方式,建议放在子线程中执行,否则会卡住界面。但有时还是需要阻塞执行,如进入欢迎界面需要沉睡3秒才进入主界面时。
没有找到取消执行方式。
[NSThread sleepForTimeInterval:2.0];