0

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

4

2 回答 2

5

是的,它将返回 null。NSUserDefaults使用属性列表文件读取和写入默认值,因此它只能管理属性列表类型:NSString, NSNumber, NSData, NSDate, NSArray, NSDictionary.

总而言之,你不能存储UILocalNotificationin NSUserDefaults

于 2012-07-05T05:53:06.017 回答
1

尝试将值手动转换为 NSDictionary 并尝试将其添加到 userdefaults。这解决了这个问题。我的意思是您可以将诸如localNotif.fireDate localNotif.repeatInterval localNotif.alertBody localNotif.soundNameetc 之类的项目转换为字符串对象并将它们设置为 NSDictionary。因此,您可以将它们保存到 userdefaults 中。`

于 2012-07-05T05:54:56.857 回答