IOS Data Persistence: Using NSUserDefaults to store data
1. Usage:NSUserDefaults is used to store data similar to user configurations and program settings.
In iOS, you can use NSUserDefault, NSKeyedArchiver, sqlite, and CoreData to store data. NSUserDefaults is used to store data similar to user configurations, the latter two users store massive and complex data.
NSUserDefault supports all native data types such as NSString, NSNumber, NSDate, NSArray, NSDictionary, BOOL, NSInteger, and NSFloat.If you want to store custom objects (such as custom class objects), you must convert them to NSData storage.
2. Usage:
NSUserDefault is easy to use:
Class A page:
NSUserDefaults * userDefault = [NSUserDefaults standardUserDefaults];
[UserDefault setObject: @ "Beijing" forKey: LASTCITY];
[UserDefault synchronize];
Page B:
NSUserDefaults * userDefault = [NSUserDefaults standardUserDefaults];
NSString * lastCity = [userDefault objectForKey: LASTCITY];
3. Usage Details:
If you want to store custom objects (such as custom class objects), you must convert them to NSData storage:
[Cpp]
- NSArray * arr = [[NSArray alloc] initWithObjects: @ arr1, @ arr2, nil]
- [MySettingData setObject: arr forKey: @ arrItem];
- [MySettingData setObject: @ admin forKey: @ user_name];
- [MySettingData setBOOL: @ YES forKey: @ auto_login];
- [MySettingData setInteger: 1 forKey: @ count];
After adding data to NSUserDefaults, they become global variables, and the data in NSUserDefault can be read and written in the App:
[Cpp]
- NSUserDefaults * mySettingDataR = [NSUserDefaults standardUserDefaults];
- NSLog (@ arrItem =%@, [mySettingDataR objectForKey: @ arrItem]);
- NSLog (@ user_name =%@, [mySettingDataR objectForKey: @ user_name]);
- NSLog (@ count = % d, [mySettingDataR integerForKey: @ count]);
To delete a data item, you can use removeObjectForKey to delete the data:
[Cpp]
- [MySettingData removeObjectForKey: @ arrItem];
It should be noted that NSUserDefaults regularly writes data in the cache to the disk, rather than writing data instantly. To prevent data loss caused by program exit after NSUserDefaults is written, you can use synchronize to force data to be written to the disk immediately after data is written:
[Cpp]
- [MySettingData synchronize]; after running the preceding statement, the data in NSUserDefaults is written. in the plist file, if the program is run on the simulator, you can find a plist file named YOUR-USERNAME under the/Users/YOUR-APP-DIR/Library/Application Support/iPhone Simulator/4.1/Applications/YOUR-Bundle_Identifier.plist/Library/Prefereces directory for Mac, open the file with Xcode and you can see the data you just written.
4. You can rewrite the object or data corresponding to the same keyword. After rewriting, the keyword corresponds to a new object or data, and the old object or data is automatically cleared.