Most efficient way of implementing an alarm on iPhone
I have implemented a simple clock like so:
- (void)runTimer {
timer = [NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(showActivity)
userInfo:nil
开发者_C百科 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?
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];
You can use initWithFireDate
method
精彩评论