可以UILocalNotification
存储NSUserDefaults
吗?
我试图获取值,但它总是返回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。
答案 0 :(得分:5)
是的,它将返回null。 NSUserDefaults
使用属性列表文件读取和写入默认值,因此它只能管理属性列表类型:NSString
,NSNumber
,NSData
,NSDate
,{ {1}},NSArray
。
总而言之,您无法在NSDictionary
中存储UILocalNotification
。
答案 1 :(得分:1)
尝试将值手动转换为NSDictionary,并尝试将其添加到userdefaults。这解决了这个问题。
我的意思是你可以转换像localNotif.fireDate
这样的项目
localNotif.repeatInterval
localNotif.alertBody
localNotif.soundName
等等到字符串对象中并将它们设置为NSDictionary。因此,您可以将它们保存到用户默认中。
`