倾听当前周的变化?

时间:2011-04-10 13:15:28

标签: macos event-handling nsdate

我在OS X中为自己测试了一些东西,我想知道最好的方法是什么。

我有一个返回当前周数的方法。

-(NSInteger) getWeekNumber {
  NSDate *date = [NSDate date];
  NSCalendar *calendar = [NSCalendar currentCalendar];
  NSDateComponents *components = [calendar components:NSWeekCalendarUnit fromDate:date];

  return [components week];
}

由于这只会每周发生一次,所以有一个线程会每隔一秒左右刷一次我的标签,但我希望标签值在第二周的数字更改时改变。

我还想用当前时间更新标签,实际上是每秒一次,或者每分钟更新一次,具体取决于设置。这只是一个每秒运行一次的线程吗?

1 个答案:

答案 0 :(得分:1)

没有必要使用线程来完成这些简单的任务 NSTimer是一种方法,为每周更新做一些这样的事情:

// Exact moment the new week starts
NSDate *date = 

// Imagine the new week starts in 5 seconds
NSDate *date = [NSDate dateWithTimeIntervalSinceNow:5]; 

NSTimer *timer = [[NSTimer alloc]
                  initWithFireDate: date
                  interval: 60*60*24*7 // Equals one week
                  target: self
                  selector: @selector(updateWeekLabel:)
                  userInfo: nil
                  repeats: NO
                  ];

[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];

新周开始时将触发以下功能:

-(void)updateWeekLabel:(NSTimer*)theTimer
{
    // Get current week and update the label.
    // Wait for next week or invalidate the timer like this:
    [theTimer invalidate];
}

在时钟上使用这样的东西:

NSTimer *timer = [NSTimer 
                  scheduledTimerWithTimeInterval: 1 
                  target: self 
                  selector: @selector(updateTimeLabel:) 
                  userInfo: nil 
                  repeats: YES
                  ];

[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];

每秒触发此功能:

-(void)updateTimeLabel:(NSTimer*)theTimer
{
    // Get current time and update the label.
}
相关问题