NSUserDefaults拒绝保存

时间:2015-01-18 14:36:05

标签: ios objective-c nsuserdefaults

启动一个新的单一视图项目并更新主ViewController的viewDidLoad。目的是检索并增加存储在NSUserDefaults中的值并保存它。

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSString *key = @"kTheKey";

    NSNumber *number = [[NSUserDefaults standardUserDefaults] objectForKey:key];
    NSLog(@"current value is %@", number);

    NSNumber *incremented = @(number.integerValue + 1);
    NSLog(@"new value will be %@", incremented);

    [[NSUserDefaults standardUserDefaults] setObject:incremented forKey:key];
    [[NSUserDefaults standardUserDefaults] synchronize];

    NSLog(@"reboot");
}

如果我强行从Xcode退出应用程序(或在实际使用中重新启动设备),则通常不会保存默认值。以下是一些示例输出:

current value is (null)
new value will be 1
reboot
current value is 1
new value will be 2
reboot
current value is 1
new value will be 2
reboot

似乎有一些时间组件 - 如果我在重新启动前等待3秒以上,则默认情况下更有可能保存。请注意,在停止执行之前等待几秒钟,第一次执行是“允许”保存的。第二次执行在第一个或第二个秒中停止,导致第三次运行中记录的值保持不变。这可以在运行iOS 8.1的iPad Air 2上重新生成。

有什么可以解释这个?

1 个答案:

答案 0 :(得分:1)

这是正常行为。

用户默认值排队等待保存。当你强行退出"这个应用程序你没有给它时间。

我认为在Xcode上你的意思就是停止。你提到退出(0);。事情都不正常"到iOS应用程序。不应在iOS应用程序中执行此类强制退出。

当用户以正常方式退出应用程序(多任务视图并向上滑动应用程序)时,它实际上并没有立即退出。它会从视图中删除,就像它一样。但是之后用户默认值会被写出来。最多几秒钟后。当他们点击主页按钮时也一样。

文档完整地解释了应用程序生命周期。使用消息。并且当收到这些消息时,您应该强制清除默认值。像这样输入初始化或ViewDidLoad:

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(movingToBackground:) name:UIApplicationWillResignActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(movingToForeground:) name:UIApplicationDidBecomeActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateDefaults:) name:UIApplicationWillTerminateNotification object:nil];

然后像这样创建方法movingToBackgroundmovingToForegroundupdateDefaults

-(void) updateDefaults: (NSNotification *) notification {
     [[NSUserDefaults standardUserDefaults] synchronize];
}