NSUserDefaults返回null

PTC*_*CHR 0 iphone objective-c nsuserdefaults ios 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");
    }
}
Run Code Online (Sandbox Code Playgroud)

这是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];
}
Run Code Online (Sandbox Code Playgroud)

oldNotifObj始终返回null.

小智 5

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

总之,你不能存储在UILocalNotificationNSUserDefaults.