objective-c - 如何使用 NSTimer?

如何使用 NSTimer?谁能给我一步一步的指导?

最佳答案

首先,我想提请您注意 Cocoa/CF 文档(它始终是一个很好的第一站)。 Apple 文档在每篇引用文章的顶部都有一个名为“配套指南”的部分,其中列出了正在记录的主题的指南(如果有的话)。例如,对于 NSTimer,the documentation列出了两个配套指南:

  • Timer Programming Topics for Cocoa
  • Threading Programming Guide

对于您的情况,计时器编程主题文章可能是最有用的,而线程主题与所记录的类相关但不是最直接相关的。如果你看一下 Timer Programming Topics 文章,它分为两部分:

  • 计时器
  • 使用计时器

对于采用这种格式的文章,通常会概述类及其用途,然后是一些关于如何使用它的示例代码,在这种情况下,在“使用计时器”中“部分。有关于“创建和调度计时器”、“停止计时器”和“内存管理”的部分。从文章中,可以像这样创建一个计划的、非重复的计时器:

[NSTimer scheduledTimerWithTimeInterval:2.0
    target:self
    selector:@selector(targetMethod:)
    userInfo:nil
    repeats:NO];

这将创建一个在 2.0 秒后触发的计时器,并使用一个参数调用 self 上的 targetMethod:,该参数是一个指向 NSTimer的指针实例。

如果您想更详细地了解该方法,您可以引用文档以获取更多信息,但也有围绕代码的解释。

如果你想停止一个重复的计时器,(或在它触发之前停止一个非重复的计时器),那么你需要保留一个指向已创建的 NSTimer 实例的指针;通常这需要是一个实例变量,以便您可以在另一种方法中引用它。然后,您可以在 NSTimer 实例上调用 invalidate:

[myTimer invalidate];
myTimer = nil;

nil 出实例变量也是一种很好的做法(例如,如果多次调用使计时器无效的方法并且实例变量尚未设置为 nil 并且 NSTimer 实例已被释放,它会抛出异常)。

还要注意文章底部关于内存管理的要点:

Because the run loop maintains the timer, from the perspective of memory management there's typically no need to keep a reference to a timer after you’ve scheduled it. Since the timer is passed as an argument when you specify its method as a selector, you can invalidate a repeating timer when appropriate within that method. In many situations, however, you also want the option of invalidating the timer—perhaps even before it starts. In this case, you do need to keep a reference to the timer, so that you can send it an invalidate message whenever appropriate. If you create an unscheduled timer (see “Unscheduled Timers”), then you must maintain a strong reference to the timer (in a reference-counted environment, you retain it) so that it is not deallocated before you use it.

https://stackoverflow.com/questions/1449035/

相关文章:

ios - 如何删除 UITableView 中的空单元格?

objective-c - 使用 alloc init 而不是 new

objective-c - 如何按比例缩放 UIImageView?

objective-c - objectForKey 和 valueForKey 的区别?

objective-c - 如何在 Objective-C 中反转 NSArray?

objective-c - 我的 Objective-C 单例应该是什么样的?

ios - 在 Objective-C 中使用 GCD 的 dispatch_once 创建单例

objective-c - "sending ' 常量 NSString * ' to parame

objective-c - Xcode 的隐藏功能

ios - 何时使用 NSInteger 与 int