开发者

call a method with NSDate?

Im writing a simple clock app and am looking for a way to call a method when the hour changes (or minute of second etc etc). If someone could point me in the right direction for this i would much appreciate it.Per开发者_运维百科haps the kind of instance that calls a method for an alarm, im not sure?


You could schedule an NSTimer with -initWithFireDate:..., with the fire date set to whole hours.


If you're writing a clock app with precision down to seconds for humans, it is easier to ignore sub-second differences and use +scheduledTimerWithTimeInterval:... directly, e.g.

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

-(void)updateClock {
  NSDate* now = [NSDate date];
  NSCalendar* calendar = [NSCalendar currentCalendar];
  NSDateComponents* dateComps = [calendar components:NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit
                                            fromDate:now];

  NSInteger hourNow = [dateComps hour];
  NSInteger minuteNow = [dateComps minute];
  NSInteger secondNow = [dateComps second];
  // update clock view using 'hourNow', 'minuteNow' and 'secondNow'
  if (secondNow == 0) {
     // whole minute
     if (minuteNow == 0) {
        // whole hour
     }
     // (note: not very reliable since a timer does not need to fire on schedule)
} 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜