【问题标题】:Invalidating instanced NSTimers使实例化的 NSTimers 无效
【发布时间】:2026-01-22 00:45:02
【问题描述】:

我有一个UIScrollView,由UILabels 填充,每个页面上由NSTimers 更新,由NSDictionary 填充

for (id key in _infoDict) {

        NSTimer *releaseDateTimer = [NSTimer scheduledTimerWithTimeInterval: 1.0 target: self
                                                              selector: @selector(calculateReleaseDate:) userInfo: dateInfo repeats: YES];
        [self.releaseDateTimer fire];

}

正在刷新的 UILabel 都由它们的标签引用,这些标签基于它们所在的页面和日历单元。

-(void)calculateReleaseDate:(NSTimer*)theTimer {

        NSString *monthString = [[NSString alloc]initWithFormat:@"%i",[finalDate month]];
        NSString *dayString = [[NSString alloc]initWithFormat:@"%i",[finalDate day]];
        NSString *hourString = [[NSString alloc]initWithFormat:@"%i",[finalDate hour]];
        NSString *minutesString = [[NSString alloc]initWithFormat:@"%i",[finalDate minute]];
        NSString *secondsString = [[NSString alloc]initWithFormat:@"%i",[finalDate second]];

        UILabel *monthValue = (UILabel*)[self.scrollView viewWithTag:[monthTag intValue]];
        [monthValue setText:monthString];

        UILabel *dayValue = (UILabel*)[self.scrollView viewWithTag:[dayTag intValue]];
        [dayValue setText:dayString];

        UILabel *hourValue = (UILabel*)[self.scrollView viewWithTag:[hourTag intValue]];
        [hourValue setText:hourString];

        UILabel *minValue = (UILabel*)[self.scrollView viewWithTag:[minTag intValue]];
        [minValue setText:minutesString];

        UILabel *secValue = (UILabel*)[self.scrollView viewWithTag:[secTag intValue]];
        [secValue setText:secondsString];

}

这不是完整的方法,但你明白了。 现在,我想通过删除所有UIScrollView 子视图然后重新填充它来重建整个页面。

这就是我的问题所在,我的标签值在数字之间跳跃。 我只能假设我之前创建的计时器的实例仍在访问这些标签。

有没有办法访问 runloop 上的计时器并在它们上运行 [NSTimer invalidate]; 或者我要解决这一切都错了。

我们将不胜感激。

【问题讨论】:

  • 当然!很简单。谢谢你。如果您回答不好,请将其标记为已回答。
  • 我添加了我的评论作为答案。

标签: ios objective-c nstimer


【解决方案1】:

您可以在 for 循环中的 NSMutableArray 中添加 NSTimer 实例。然后,如果它们在另一个 for 循环中仍然有效,您可以使它们无效。您可以使用 isValid 方法检查 NSTimer 是否仍然有效。

【讨论】: