gpt4 book ai didi

ios - NSTimer 的 isValid 总是返回 YES

转载 作者:行者123 更新时间:2023-12-01 18:11:20 27 4
gpt4 key购买 nike

所以我有一个计时器,它是 不是 重复的。每次触发时,正在执行的方法会根据我的应用程序的某些内部逻辑决定是否重新安排它。

此方法可从应用程序的其他部分使用,因此我在该方法中所做的第一件事是检查计时器是否仍然有效(了解发起者是计时器还是其他实体),以防万一不是由我想让它失效的计时器启动的:

if (self.pollingTimer.isValid) {
[self.pollingTimer invalidate];
self.pollingTimer = nil;
}

我注意到如果由于计时器被触发而调用该方法 - 我总是从 isValid 收到一个真实值属性,即使查看 NSTimer scheduledTimerWithTimeInterval:(NSTimeInterval)seconds target:(id)target selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)repeats 下的文档方法:

repeats
If YES, the timer will repeatedly reschedule itself until invalidated. If NO, the timer will be invalidated after it fires.

Discussion
After seconds seconds have elapsed, the timer fires, sending the message aSelector to target.



我很难理解计时器何时自动失效,这让我想到了我的问题:
  • 知道为什么我总是从 isValid 得到 YES 吗?
  • 的确切定义是什么计时器触发 ?它只是按照文档中的说明将消息 aSelector 发送到目标吗?还是正在完成该方法的执行? (这可以解释我的经历)

  • 提前致谢。

    最佳答案

    定时器不是实时机制;它仅在已添加计时器的运行循环模式之一正在运行并且能够检查计时器的触发时间是否已过时触发。因此,计时器不会立即使自己失效,而是在运行循环结束时。
    作为一个简单的测试,您可以看到:

    - (void)viewDidLoad {
    [super viewDidLoad];
    _timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(timerFired) userInfo:nil repeats:NO];

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    if (self.timer.isValid){
    NSLog(@"--> TIMER VALID");
    } else {
    NSLog(@"TIMER INVALID!");
    }
    });
    }

    - (void) timerFired {
    if (self.timer.isValid){
    NSLog(@"--> TIMER VALID");
    } else {
    NSLog(@"TIMER INVALID!");
    }
    }
    这将记录 --> TIMER VALID来自 timerFired方法和来自 dispatch_after 的 block 时被调用,你会看到 TIMER INVALID! .因此,当您使用 repeats:NO 安排计时器时, 它 保证不重新安排自己,但它不会立即失效。
    所以,回答你的问题:

    repeats

    If YES, the timer will repeatedly reschedule itself untilinvalidated. If NO, the timer will be invalidated after it fires (but not immediately)

    关于ios - NSTimer 的 isValid 总是返回 YES,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30614564/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com