可可倒数计时器

发布于 2024-08-02 08:38:18 字数 590 浏览 2 评论 0原文

我想知道是否有某种方法可以创建一个从给定时间开始倒计时的计时器。例如,假设我希望这个计时器持续一个小时。将有一个 NSTextField 显示剩余时间(例如 25 分钟),并每分钟自动更新为新值。然后,当一个小时最终过去时,它将运行一些功能。我看到有人为此建议 NSTimer 和 NSDate,但我想知道你们都有什么建议。

谢谢!

编辑:我当前的代码(timeInstance是一个实例变量):

- (void)awakeFromNib:
{
timeInstance = [[NSDate date] addTimeInterval:(10 * 60)];
[timeInstance retain];

[timer invalidate];
timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timer:) userInfo:NULL repeats:YES];
}

- (void)timer:(NSTimer *)myTimer
{
NSDate *now = [NSDate date];
// Compare
}

I am wondering if there is some way that I can create a timer that countdown from a given time. For example, say I want this timer to last an hour. There will be a NSTextField that will show the time remaining (ex. 25 minutes), and will auto update every minute to the new value. And then, when an hour is finally passed, it will run some function. I have seen people suggesting NSTimer and NSDate for this, but am wondering what you all could suggest.

Thanks!

EDIT: My current code (timeInstance is an instance variable):

- (void)awakeFromNib:
{
timeInstance = [[NSDate date] addTimeInterval:(10 * 60)];
[timeInstance retain];

[timer invalidate];
timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timer:) userInfo:NULL repeats:YES];
}

- (void)timer:(NSTimer *)myTimer
{
NSDate *now = [NSDate date];
// Compare
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

吾家有女初长成 2024-08-09 08:38:18

NSTimer 和 NSDate 听起来非常合理。

编辑:作为旁注,随着目标时间的临近增加频率可能是一个好主意;允许您从小时显示更改为分钟显示再到秒显示。

NSTimer and NSDate sounds perfectly reasonable.

EDIT: As a side note, it might be a good idea to increase the frequency as the target time approaches; allowing you to change from hour display to minute display to second display.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文