iOS - 读取旧值的nsuserdefault

时间:2017-03-15 11:19:41

标签: ios objective-c nsuserdefaults

我在nsuserdefault上保存并删除字典。

只是保存,一切顺利。

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))handler {
     NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
     NSData *myData = [NSKeyedArchiver archivedDataWithRootObject:userInfo];
    [prefs setObject:stored forKey:key];
}

在viewController中

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSData *data = [prefs objectForKey:key];
[prefs removeObjectForKey:key];
//I check here with debugger [prefs objectForKey:key] is returning nil
//doing stuff with data
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
OtherViewController *controller = [storyboard instantiateViewControllerWithIdentifier:@"OtherViewController"];
controller.user = user;
[self parentShowViewController:controller sender:nil];

在OtherViewController viewDidLoad方法中:

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSData *data = [prefs objectForKey:key];
//Data has its old value and different to nil
//WHYY!!!!!!!

在我的iPhone 6S上测试

更新

我在保存之后和读取之前添加了[prefs synchronize],但仍然失败。

1 个答案:

答案 0 :(得分:0)

更改您的ViewController code,如下所示。

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    NSData *data = [prefs objectForKey:key];
    [prefs removeObjectForKey:key];
    [prefs synchronize];
    //I check here with debugger [prefs objectForKey:key] is returning nil
    //doing stuff with data
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    OtherViewController *controller = [storyboard instantiateViewControllerWithIdentifier:@"OtherViewController"];
    controller.user = user;
    [self parentShowViewController:controller sender:nil];