iOS中耽误实验一样平常有三种方法:performSelector,NSTimer,dispatch_after
一:performSelector
耽误方法:[self performSelectorselector(startP) withObject:nil afterDelay:3.0];
取消耽误:
方法一:这里须要注意参数需保持同等,否则取消散败
[NSObject cancelPreviousPerformRequestsWithTarget:self selectorselector(startP) object:nil];
方法二:可以取消全部的耽误调用
[NSObject cancelPreviousPerformRequestsWithTarget:self ];
大概碰到的标题:cancelPreviousPerformRequestsWithTarget不管用,计时依然实验,这是由于performSelector和cancelPreviousPerformRequestsWithTarget必须在同一个线程中实验才可以
dispatch_async(dispatch_get_main_queue(),^{
[NSObject cancelPreviousPerformRequestsWithTarget:self selectorselector(startP) object:nil];
//大概
//[NSObject cancelPreviousPerformRequestsWithTarget:self ];
});
二:NSTimer
耽误方法:
self.timer=[NSTimer scheduledTimerWithTimeInterval:3.0 target:self selectorselector(startP) userInfo:nil repeats:NO];
取消方法:[self.timer invalidate];self.timer=nil;
三:dispatch_after
耽误方法:
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{//主线程
//要实验的利用//耽误两秒后实验
});
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_global_queue(), ^{
//要实验的利用//耽误两秒后实验
});
暂无取消
四:sleepForTimeInterval
[NSThread sleepForTimeInterval:1];
这个方法会壅闭主线程 |