在 iPhone 上实现闹钟的最有效方法

发布于 2024-09-10 04:41:10 字数 735 浏览 6 评论 0原文

我已经实现了一个简单的时钟,如下所示:

- (void)runTimer {

    timer = [NSTimer scheduledTimerWithTimeInterval:1.0 
                                             target:self 
                                           selector:@selector(showActivity) 
                                           userInfo:nil 
                                            repeats:YES];

}

- (void)showActivity {

    NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];
    NSDate *date = [NSDate date];

    [df setDateFormat:@"HH:mm"];

    [clock setFont:digitalFont];

    [clock setText:[df stringFromDate:date]];

}

它基本上只是每秒运行一次以更新 UILabel 中的时间的任务。现在,如果我想扩展这个时钟以在某些时间做出反应,就像闹钟一样,该怎么办? 持续检查 NSDate 的值似乎很耗电。我该怎么做?

I have implemented a simple clock like so:

- (void)runTimer {

    timer = [NSTimer scheduledTimerWithTimeInterval:1.0 
                                             target:self 
                                           selector:@selector(showActivity) 
                                           userInfo:nil 
                                            repeats:YES];

}

- (void)showActivity {

    NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];
    NSDate *date = [NSDate date];

    [df setDateFormat:@"HH:mm"];

    [clock setFont:digitalFont];

    [clock setText:[df stringFromDate:date]];

}

It's basiclly just a task that is run every second to update the time in a UILabel. Now what if I would like to extend this clock to react on certain times, just like a alarm clock.
Continously checking the value of NSDate seems battery intensive. How would I do this?

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

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

发布评论

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

评论(2

错々过的事 2024-09-17 04:41:11

您可以使用 initWithFireDate 方法

You can use initWithFireDate method

誰ツ都不明白 2024-09-17 04:41:10

实现这一目标的最简单方法是什么?只需将另一个 NSTimer 设置为在警报发生时触发即可。

NSTimer* myTimer = [[NSTimer alloc] initWithFireDate:(NSDate *)date
                                            interval:(NSTimeInterval)seconds
                                              target:(id)target
                                            selector:(SEL)aSelector
                                            userInfo:(id)userInfo
                                             repeats:(BOOL)repeats];

The simplest way to achieve this? Just have another NSTimer that is set to fire at the time of the alarm.

NSTimer* myTimer = [[NSTimer alloc] initWithFireDate:(NSDate *)date
                                            interval:(NSTimeInterval)seconds
                                              target:(id)target
                                            selector:(SEL)aSelector
                                            userInfo:(id)userInfo
                                             repeats:(BOOL)repeats];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文