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];
}
.....
}
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With