zl程序教程

您现在的位置是:首页 >  其它

当前栏目

OC:四种延时触发的方式

方式 四种 触发 延时 OC
2023-09-27 14:27:09 时间

方式一(performSelector)

[self performSelector:@selector(myMethod) withObject:nil afterDelay:3.0]

取消要执行的方法,有点像 clearTimeout

[NSObject cancelPrevIoUsPerformRequestsWithTarget:self selector:@selector(myMethod) object:nil];

方式二(NSTimer)

// NO表示只调用一次,YES表示循环调用
_timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(delayAction) userInfo:nil repeats:NO];

-(void)delayAction
{
   NSLog(@"qqqqqqqqqq");
}

在页面销毁的时候要把Timer也销毁掉以免内存泄漏:

_timer = nil;
[_timer invalidate];

系统没有为NSTimer提供取消延迟执行的方法,即使把Timer销毁掉,延迟的方法依然会执行。但是我们可以在延迟执行的方法内加一个判断来控制是否执行:

if (_timer) {
    NSLog(@"delay action");
}

方式三(GCD)

dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
     [self delayAction];
 });

通过dispatch_after同样无法取消延迟执行的方法,可是参照着timer的思路,我们同样可以自己设置一个标记来控制延迟执行的操作:
设置一个BOOL值初始值为NO:

@property (nonatomic, assign) BOOL isDelay;

延迟操作:

dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
    [self delayAction];
});

要延迟的方法内部:

if (_isDelay == NO) {
   NSLog(@"delay action");
}

这样便可通过设置 isDelay = YES; 来取消延迟操作了。

方式四(NSThread)

把当前线程进入睡眠状态,到时间后自动唤醒,继续往下执行,但并不能主动进行唤醒操作。

[NSThread sleepForTimeInterval:2];

参考文档

https://blog.csdn.net/liu1347508335/article/details/52352848