Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saved data lost after kill app using NSUserDefaults

I use NSUserDefaults in my setting. App works well even I press home key let app into background, but if I kill the app, the data save in NSUserDefaults will lost. Here is my code. I have use synchronize. The First initialize:

 if (![userDefaults integerForKey:
          kORFootageAirPlayModeKey])
    {
        [userDefaults setInteger:TRUE forKey:kORFootageAirPlayModeKey];
    }
    [userDefaults synchronize];

Read value out in a viewController:

airPlayMode = [[NSUserDefaults standardUserDefaults]integerForKey:kORFootageAirPlayModeKey];

Set it in a action:

- (IBAction)changeAirPlayStatus:(id)sender
{

    if (sender)
    {
        airPlayMode = [sender tag];

        [[NSUserDefaults standardUserDefaults] setInteger:airPlayMode forKey:kORFootageAirPlayModeKey];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
.....

}

like image 868
kevin young Avatar asked Jul 16 '12 14:07

kevin young


People also ask

How much data can you store in NSUserDefaults?

It appears the limit is the maximum file size for iOS (logically), which is currently 4GB: https://discussions.apple.com/thread/1763096?tstart=0. The precise size of the data is circumscribed by the compiler types (NSData, NSString, etc.) or the files in your asset bundle.

Is NSUserDefaults secure?

Because NSUserDefaults stores all data in an unencrypted . plist file, a curious person could potentially view this data with minimal effort. That means that you should never store any type of sensitive data inside NSUserDefaults.

How do you check if NSUserDefaults is empty in Objective C?

There isn't a way to check whether an object within NSUserDefaults is empty or not. However, you can check whether a value for particular key is nil or not.

How do you save NSUserDefaults in Objective C?

static func setObject(value:AnyObject ,key:String) { let pref = NSUserDefaults. standardUserDefaults() pref. setObject(value, forKey: key) pref. synchronize() } static func getObject(key:String) -> AnyObject { let pref = NSUserDefaults.


1 Answers

The best way to ensure that your data are saved is include a call to -synchronize in applicationWillTerminate: and in applicationWillResignActive: in your application delegate.

Edit:

Also, steipete's comments about using setInteger:TRUE are accurate- use setBool:YES instead.

like image 135
eric.mitchell Avatar answered Oct 04 '22 02:10

eric.mitchell