iOS provides a lightweight, fast data storage method: Nsuserdefaults;
When the program runs, it reads the program settings from the user's default database, while the nsuserdefaults cache avoids opening the user's default database every time the data is read, all the data is in memory, and read and write is fast.
Nsuserdefaults is a singleton, in the whole program only one instance object, he can be used for the permanent preservation of data, and simple and practical, this is it can let the data free transfer of a premise, but also people like to use it to save simple data one of the main reasons.
When using Nsuserdefaults to store custom objects initially, we must recognize what types of data nsuserdefaults can store, listed below:
NSUserDefaults支持的数据类型有:NSNumber(NSInteger、float、double),NSString,NSDate,NSArray,NSDictionary,BOOL.
[NSUserDefaults standardUserDefaults]用来记录一下永久保留的数据非常方便,不需要读写文件,而是保留到一个NSDictionary字典里,由系统保存到文件里,系统会保存到该应用下的/Library/Preferences/gongcheng.plist文件中。需要注意的是如果程序意外退出,NSUserDefaultsstandardUserDefaults数据不会被系统写入到该文件,不过可以使用[[NSUserDefaultsstandardUserDefaults] synchronize]命令直接同步到文件里,来避免数据的丢失。
1. Get Nsuserdefaults
//这是一个单例,获取非常方便,随时可以调用: [NSUserDefaults standardUserDefaults];
2. Write Data
[[NSUserDefaults standardUserDefaults] setInteger:10 forKey:@"test"]; [[NSUserDefaults standardUserDefaults] setFloat:10.0 forKey:@"test"]; //..... NSUserDefaults 支持多种数据类型,用 key来标示
3. Read the data
int a = [[NSUserDefaults standardUserDefaults] integerForKey:@"test"]; float b = [[NSUserDefaults standardUserDefaults] floatForKey:@"test"];
。。。当然也支持其他各种类型
4. Save data for persistent storage
[[NSUserDefaults standardUserDefaults]synchronize];
5. Determine if the data exists
if([[NSUserDefaults standardUserDefaults] objectForKey:@""test"]==nil){ //代码处理 }else{ //代码处理 }
A database, such as SQLite, is suitable for storing large amounts of data.
iOS development-nsuserdefaults Lightweight Fast Storage