应用程序强制退出时,Xcode NSUserDefaults设置丢失

时间:2015-10-23 18:54:23

标签: ios xcode nsuserdefaults

我正在使用NSUserDefaults来保存BOOL,这些BOOL表示映射的注释是否是“最喜欢的”。当用户退出应用程序然后重新启动它时,BOOL正确保存。但是,当用户强制退出(按两次主页按钮并在应用程序上向上滑动)应用程序时,NSUserDefaults将丢失。有人可以解释为什么会这样吗?我正在使用Xcode v7.0。

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {

// If annotation is displayed, the User can save/clear annotation as a favorite
if ((_acmeMotorsIsDisplayed == YES) && (_acmeMotorsIsFavorite == YES)){
            _acmeMotorsIsFavorite = NO;
            [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"acmeMotorsIsFavorite"];
        }
else if ((_acmeMotorsIsDisplayed == YES) && (_acmeMotorsIsFavorite == NO)){
            _acmeMotorsIsFavorite = YES;
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"acmeMotorsIsFavorite"];
        }
}

-(void)loadUserDefaults{
// One of many lines of code that load user default settings
_acmeMotorsIsFavorite = [[NSUserDefaults standardUserDefaults] boolForKey:@"acmeMotorsIsFavorite"];
}

-(void)viewDidLoad {
    [self loadUserDefaults];
}

2 个答案:

答案 0 :(得分:1)

我认为你忘记了synchronize方法。

NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setBool:NO forKey:@"acmeMotorsIsFavorite"];
[userDefaults synchronize];

答案 1 :(得分:1)

当用户双击Home时,调用app delegate方法applicationWillResignActive:,此时同步NSUserDefaults

- (void)applicationWillResignActive:(UIApplication *)application {
    [[NSUserDefaults standardUserDefaults] synchronize];
}