秒表-NSTimer或NSDate [英] Stopwatch - NSTimer or NSDate

查看:85
本文介绍了秒表-NSTimer或NSDate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现一个每秒计数的计时器.我有2种方法,但是对于哪种方法是最佳选择感到有些困惑.它使用NSTimer或NSDate,据我了解,NSTimer通常仅用于触发方法,所以也许我不应该使用NSTimer而是NSDate?

I want to implement a timer that counts up every second. I have 2 ways in mind, but am kinda confused about which one is the optimal way to do it. It's either using NSTimer or NSDate, and as I understand NSTimer is usually only used to fire methods, so maybe I shouldn't use NSTimer but NSDate?

请多加澄清,谢谢.

推荐答案

NSDate 是模型类.除了代表特定的日期和时间,它不会执行任何操作.秒表必须同时使用( NSTimer NSDate ).启动手表时,将当前日期保存在 NSDate 实例中,并以1秒钟的间隔(如果要显示毫秒,则需要更长的时间)启动NSTimer.而且,每当计时器启动时,您就可以计算当前日期和保存日期之间的时差并将其显示给用户.

NSDate is a model class. It doesn't fire or do anything except represent a certain date and time. You will have to use both (NSTimer and NSDate) for you stopwatch. When you start the watch save the current date in an NSDate instance and start an NSTimer with a 1 sec interval (or more if you want to display milliseconds). And everytime the timer fires, you calculate the difference between the current date and the saved date and show it to the user.

这篇关于秒表-NSTimer或NSDate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆