2013-04-24 19 views
0

我需要我的應用程序在一天中的某個特定時間運行方法,我認爲最好的方法是設置一個通知時間。我以前使用過NSNoticationCenter,但我不確定如何在一天中的某個時間進行設置。NSNotication在一天中的時間

編輯: 我正在用不同的方式使用NSTimer。這裏是我的代碼

NSCalendar* myCalendar = [NSCalendar currentCalendar]; 
NSDateComponents* components = [myCalendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit 
              fromDate:[NSDate date]]; 
[components setHour: 10]; 
[components setMinute: 5]; 
[components setSecond: 0]; 
NSDate *date = [myCalendar dateFromComponents:components]; 

NSTimer *t = [[NSTimer alloc] initWithFireDate:date 
             interval:0.0 
             target:self 
             selector:@selector(fired:) 
             userInfo:nil 
             repeats:YES]; 
[[NSRunLoop mainRunLoop] addTimer:t forMode:NSDefaultRunLoopMode]; 

回答

0

使用NSTimer類的方法。創建計時器對象並相應地設置啓動日期。在定時器回調方法實現方法中發佈所需的通知。

另一種方法是使用performSelector:withObject:afterDelay:。在選擇器方法中發佈需要的通知。

+0

有了NSTimer,我可以把一天中的哪個時間點火嗎? – Jonathan 2013-04-25 20:03:09

+0

您可以使用initWithFireDate:interval:target:selector:userInfo:重複init方法。這需要NSDate參數,其中您指定在一天中的哪個時間點擊該定時器。 'setFireDate:'方法可用於更改計時器fireDate後期階段。 – Raviprakash 2013-04-26 04:37:54

+0

好吧,這是有道理的,我該如何告訴它什麼時候開火? – Jonathan 2013-04-26 15:14:28