秒表 – NSTimer或NSDate

我想实现一个计时器,每秒计数。 我有两种方法,但有点困惑,哪一个是最佳的方式来做到这一点。 它要么使用NSTimer或NSDate,据我所知NSTimer通常只用于发射方法,所以也许我不应该使用NSTimer,但NSDate?

一些澄清,将不胜感激,谢谢。

NSDate是一个模型类。 除了表示特定的date和时间之外,它不会触发或做任何事情。 你将不得不同时使用( NSTimerNSDate )秒表。 当您开始手表时,将当前date保存在NSDate实例中,并以1秒为间隔启动一个NSTimer(如果要显示毫秒,则启动一个NSTimer)。 每次计时器启动时,计算当前date和保存date之间的差异并显示给用户。

使用NSTimer定期更新您的用户界面。 使用NSDate获取每个更新的精确时间。

你可能需要NSTimer。 它将等待一段时间,然后将事件触发到指定的对象。 NSDate只是给你一个不可改变的时间点。 请检查文档。 谢谢!

https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nstimer_Class/Reference/NSTimer.html

https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nsdate_Class/Reference/Reference.html

你什么意思是“数起来”? 当它“计数”时,你想要做什么?

基本上,你总是可以使用NSDate来存储一个“开始date”,然后当你觉得你可以得到“现在”和存储date之间的差异。

另一方面,如果你想在屏幕上显示一个滴答声的时钟,你可以使用一个NSTimer,每秒触发一次,告诉你的应用程序更新时钟。

几乎没有用于某个整数variables的用例,这个variables每秒都会增加而没有任何人在查看它。

我会使用NSTimer。 你可以启动计时器

 [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateSeconds)userInfo:nil repeats:YES]; 

并在你的updateSeconds方法中:

 (void)updateSeconds { int seconds = [self.secondsLabel.text intValue]; seconds = seconds + 1; self.secondsLabel.text = [NSString stringWithFormat:@"%d",seconds]; } 

请注意, secondsLabel是连接到标签的IBOutlet,以秒为单位显示已用时间。