NSUserDefaults返回null

时间:2012-07-05 05:50:54

标签: iphone objective-c ios nsuserdefaults uilocalnotification

可以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。

2 个答案:

答案 0 :(得分:5)

是的,它将返回null。 NSUserDefaults使用属性列表文件读取和写入默认值,因此它只能管理属性列表类型:NSStringNSNumberNSDataNSDate,{ {1}},NSArray

总而言之,您无法在NSDictionary中存储UILocalNotification

答案 1 :(得分:1)

尝试将值手动转换为NSDictionary,并尝试将其添加到userdefaults。这解决了这个问题。 我的意思是你可以转换像localNotif.fireDate这样的项目 localNotif.repeatInterval localNotif.alertBody localNotif.soundName等等到字符串对象中并将它们设置为NSDictionary。因此,您可以将它们保存到用户默认中。 `

相关问题