2013-10-24 27 views
0

我決定爲我的第一個應用程序創建一個警報應用程序。到目前爲止,我明白要創建兩個NSDate對象,並將它們與isEqualToDate和UILocalNotifications進行通知比較。我如何不斷比較設定日期和當前日期。我是否創建一個循環,或者在Objective C上有更高效的方法嗎?我如何不斷檢查背景?即使在應用程序之外也不斷比較兩個NSDates

[很新的目標C,對不起,謝謝你]

這是什麼iv'e開始:

NSDate * now = [NSDate date]; 
NSDate * later = [[NSDate alloc] initWithString:@"2001-03-24 10:45:32 +0600"]; 
NSComparisonResult result = [later compare:mile]; 

NSLog(@"%@", later); 
NSLog(@"%@", mile); 
+3

如果您設置了通知,您爲什麼需要比較日期?它有一個系統照顧的火災日期。 –

回答

1

你並不需要自己創建循環或比較日期。一種方法可以通過本地通知發出警報聲。一個快速的示例代碼來安排自己本地通知:

// Initialize your notification 
NSUserNotification *notification = [[NSUserNotification alloc] init]; 

// Set the title of your notification 
[notification setTitle:@"Alarm finished!"]; 

// Set the text of your notification 
[notification setInformativeText:@"My Text"]; 

// Set the time and date on which the notification will be delivered (in this case 60 seconds after the current time) 
[notification setDeliveryDate:[NSDate dateWithTimeInterval:60 sinceDate:[NSDate date]]]; 

// Set the sound, this can be either nil for no sound, NSUserNotificationDefaultSoundName for the default sound) 
[notification setSoundName:NSUserNotificationDefaultSoundName]; 

// Schedule the notification 
[[NSUserNotificationCenter defaultUserNotificationCenter] scheduleNotification:notification]; 

如果你不想使用本地通知,但要執行的東西,一旦你完成報警不同,你可以使用NSTimer來執行,一旦你的行動警報火災。

+0

有趣,但這會在一段時間後觸發一段時間。我真正想要做的是在當前時間與設定日期相同時觸發。任何提示? – Justin

+0

您需要什麼,桌面或移動設備上的通知?或者你需要觸發一個NSTimer? –

+0

@JustinShulman:你不能從字面上做你要做的事情。你不能運行代碼來檢查你的應用程序沒有運行的時間(即使你的應用程序正在運行,循環輪詢時間是非常浪費的)。您可以通過「NSTimer」爲系統提供您需要執行某些操作的日期,或者如果您的應用可能會停止運行,則可以通過本地通知進行操作。然後系統將檢查「當前時間與設置日期相同」並「觸發」您的代碼。 –