Original: http://blog.csdn.net/lxinl/article/details/11770675
The OS can use Nsuserdefaults, SQLite, coredata a few common ways to store data, Nsuserdefaults used to store similar user configuration and other such data, the latter two users to store large quantities and more complex data. The use of Nsuserdefault is relatively simple:
[CPP]View Plaincopy
- Nsuserdefaults *mysettingdata = [Nsuserdefaults standarduserdefaults];
After creating the Nsuserdefaults object, you can add data to it, which supports data types NSString, NSNumber, NSDate, Nsarray, Nsdictionary, BOOL, Nsinteger, Nsfloat, such as system-defined data types, if you want to store custom objects (such as custom class objects), you must convert them to NSData storage:
[CPP]View Plaincopy
- 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"];
When you add data to nsuserdefaults, they become global variables, and the app can read and write data from the Nsuserdefault:
[CPP]View Plaincopy < param name= "wmode" value= "Transparent" >
- Nsuserdefaults *mysettingdatar = [Nsuserdefaults standarduserdefaults];
- NSLog (@"arritem=%@", [Mysettingdatar objectforkey:@"Arritem"]);
- NSLog (@"user_name=%@", [Mysettingdatar objectforkey:@"user_name"]);
- NSLog (@"count=%d", [Mysettingdatar integerforkey:@"Count"]);
If you want to delete a data item, you can use Removeobjectforkey to delete the data:
[CPP]View Plaincopy
- [Mysettingdata removeobjectforkey:@"Arritem"];
It is important to note that the nsuserdefaults is timed to write the data in the cache to the disk, rather than the instant write, in order to prevent the data loss caused by the program exit after writing the nsuserdefaults. You can use synchronize to force the data to be written to disk immediately after the data is written:
[CPP]View Plaincopy
- [Mysettingdata Synchronize];
After running the above statement, the data in the Nsuserdefaults is written to the. plist file, and if you run the program on the emulator, you can/users/your-username/library/application the Mac support/ The IPhone simulator/4.1/applications/your-app-dir/library/prefereces directory below finds a file named Your-bundle_ Identifier.plist the plist file, open the file with Xcode and you can see the data you just wrote.
IOS data persistence using Nsuserdefaults to store data