可否將UILocalNotification
存儲在NSUserDefaults
?NSUserDefaults返回null
我試圖獲得值,但它總是返回null。
下面是試圖獲得的價值
-(IBAction)doneClicked:(id)sender
{
NSUserDefaults *prefx = [NSUserDefaults standardUserDefaults];
UILocalNotification *oldNotifObj = [prefx objectForKey:@"NotificationObject"];
NSLog(@"oldNotifObj = %@",oldNotifObj);
NSLog(@"enable notification");
if (oldNotifObj == nil)
{
[self addNotification];
NSLog(@"add a new one");
}
else
{
//if notification exist, remove old one, and add new one.
[self removeNotification:oldNotifObj];
[prefx setObject:nil forKey:@"NotificationObject"];
[self addNotification];
NSLog(@"remove old notification and add a new one");
}
}
的方法和這裏的addNotification
方法
-(void)addNotification
{
//set the notification
UILocalNotification *localNotif = [[UILocalNotification alloc]init];
localNotif.fireDate = self.timePicker.date;
localNotif.repeatInterval = NSDayCalendarUnit;
localNotif.alertBody = @"Hello world!";
localNotif.soundName = UILocalNotificationDefaultSoundName;
[[UIApplication sharedApplication]scheduleLocalNotification:localNotif];
NSLog(@"localNotif = %@",localNotif);
//saving notification to prefs
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:localNotif forKey:@"NotificationObject"];
[prefs synchronize];
}
的oldNotifObj
總是返回null。
我需要刪除通知。所以我想我需要相同的確切對象。 – PTCHR
嘗試使用NSKeyedArchiver將通知對象轉換爲nsdata。你可以使用像'NSData * data = [NSKeyedArchiver archivedDataWithRootObject:notif];'設置數據並使其使用'UILocalNotification * notif = [NSKeyedUnarchiver unarchiveObjectWithData:(NSData *)[array objectAtIndex:i]];' –
上面給出的是你可以使用'NSKeyedArchiver'的方法。請在構建之前根據您的代碼示例更改它。 –