前言
在iOS開(kāi)發(fā)中必不可少的要用到數(shù)據(jù)存儲(chǔ),數(shù)據(jù)的處理是iOS開(kāi)發(fā)中的核心技術(shù),適當(dāng)?shù)膶?duì)數(shù)據(jù)進(jìn)行持久化存儲(chǔ)可以實(shí)現(xiàn)應(yīng)用的離線功能,以此提高用戶體驗(yàn)。所謂數(shù)據(jù)持久化,就是將數(shù)據(jù)保存到硬盤中,使得在應(yīng)用程序或手機(jī)重啟后可以繼續(xù)訪問(wèn)之前保存的數(shù)據(jù)。在iOS開(kāi)發(fā)中,有很多持久化得方案,接下來(lái)我將總結(jié)以下5種持久化方案:
1、plist(屬性列表)
2、preference(偏好設(shè)置)
3、NSKeyedArchiver(歸檔)
4、SQList 3 (FMDB)
5、CoreData
由于偏好設(shè)置是將所有數(shù)據(jù)保存到preference目錄下的一個(gè)以此應(yīng)用包名來(lái)命名的plist文件中,所以將偏好設(shè)置和屬性列表放到一塊介紹。
沙盒機(jī)制
- 在介紹各種存儲(chǔ)方法之前,先說(shuō)明下沙盒機(jī)制。iOS應(yīng)用程序只能在為改程序創(chuàng)建的文件系統(tǒng)中讀取文件,不可以去其他地方訪問(wèn),此區(qū)域被稱為沙盒,所以所有的非代碼文件都要保持在此,例如圖像,圖標(biāo),聲音,屬性列表,文本文件等。
1、目錄結(jié)構(gòu)
1、“應(yīng)用程序包”
2、Documents
3、Library
Caches
Preferences
4、tmp
2、目錄結(jié)構(gòu)分析- 應(yīng)用程序包:包含所有的資源文件和可執(zhí)行文件
NSString *path = [[NSBundle mainBundle] bundlePath];
NSLog(@"%@", path); - Documents:保存應(yīng)?運(yùn)行時(shí)生成的需要持久化的數(shù)據(jù),iTunes同步設(shè)備時(shí)會(huì)備份該目錄。
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [path objectAtIndex:0];
NSLog(@"%@", path); - Library/Caches: iTunes不會(huì)同步此文件夾,適合存儲(chǔ)體積大,不需要備份的非重要數(shù)據(jù)。
NSString *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
NSLog(@"%@", path); - Library/Preferences: iTunes同步該應(yīng)用時(shí)會(huì)同步此文件夾中的內(nèi)容,通常保存應(yīng)用的設(shè)置信息。
- tmp: iTunes不會(huì)同步此文件夾,系統(tǒng)可能在應(yīng)用沒(méi)運(yùn)行時(shí)就刪除該目錄下的文件,所以此目錄適合保存應(yīng)用中的一些臨時(shí)文件,用完就刪除
NSString *path = NSTemporaryDirectory();
NSLog(@"%@", path);
- 應(yīng)用程序包:包含所有的資源文件和可執(zhí)行文件
屬性列表(plist)
iOS提供了一種plist格式的文件(屬性列表)用于存儲(chǔ)輕量級(jí)的數(shù)據(jù),屬性列表是一種XML格式的文件,拓展名為plist。如果對(duì)象是NSString、NSDictionary、NSArray、NSData、 NSNumber等類型,就可以使用writeToFile:atomically:?法 直接將對(duì)象寫到屬性列表文件中該格式保存的數(shù)據(jù)可以直接使用NSDictionary和NSArray讀取 。plist文件在iOS開(kāi)發(fā)中屬于Write寫入方式,可以以Property List列表形式顯示,也可以以xml格式顯示。對(duì)于數(shù)據(jù)管理是很方便的。掌握使用plist文件數(shù)據(jù)操作很有必要
一、將數(shù)據(jù)寫入plist文件
- 獲取文件路徑
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docPath = [path objectAtIndex:0];
NSString *myFile = [docPath stringByAppendingPathComponent:@"test.plist"]; - 存儲(chǔ)
NSArray *array = @[@"123", @"456", @"789"];
[array writeToFile:fileName atomically:YES]; - 讀取
NSArray *result = [NSArray arrayWithContentsOfFile:fileName];
NSDictionary * result = [NSDictionary dictionaryWithContentsOfFile:fileName];
NSLog(@"%@", result);
注意
只有NSString、NSDictionary、NSArray、NSData、 NSNumber等類型才能使用plist文件存儲(chǔ)。
存儲(chǔ)時(shí)使用writeToFile: atomically:方法。 其中atomically表示是否需要先寫入一個(gè)輔助文件,再把輔助文件拷貝到目標(biāo)文件地址。這是更安全的寫入文件方法,一般都寫YES。
plist文件的讀寫效率比較高,由于他的讀寫需要將所有的數(shù)據(jù)取出再全部保存,所以只適合小數(shù)據(jù)。
二、手動(dòng)添加plist文件
- 創(chuàng)建.plist文件。
新建文件-->Resource-->Property List

plist文件的根類型只能是NSArray或NSDictionary

可以在空白處右鍵“Add Row”添加數(shù)據(jù)或者點(diǎn)中“root”行,點(diǎn)擊“+”號(hào)即可添加。一般數(shù)據(jù)類型(Type)可以選擇Array、Dictionary、String等類型。同時(shí)也可以給添加的數(shù)據(jù)賦值(Value)。
除了以Property List列表形式顯示外,選中usersList.plist文件,右鍵“Open As”-“Source Code”可以以XML格式顯示。

- 將plist文件中的數(shù)據(jù)讀入對(duì)應(yīng)的根類型
//1、獲取文件所在的路徑,Resource:文件名稱、Type:文件格式
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"userInfos" ofType:@"plist"];
// 2、從路徑中獲取對(duì)應(yīng)格式的數(shù)據(jù)
// 如果Root為NSArray,則使用數(shù)組保存
NSArray *infos = [NSArray arrayWithContentsOfFile:filePath];
NSLog(@"%@",infos);
// 如果Root為NSDictionary,則使用字典保存
NSDictionary *infoDic = [NSDictionary dictionaryWithContentsOfFile:filePath];
NSLog(@"%@",infoDic);
偏好設(shè)置
一、使用NSUserDefault 實(shí)現(xiàn)持久化
下面來(lái)看下 NSUserDefault 本地保存的位置,Library/Preferences 這個(gè)目錄下的 plist 文件就是其保存的目錄。
NSUserDefault 的用法,主要是保存和讀取數(shù)據(jù)
//初始化一個(gè) NSUserDefault
+ (NSUserDefaults *)standardUserDefaults;
//設(shè)置數(shù)據(jù)的方法
- (void)setObject:(nullable id)value forKey:(NSString *)defaultName;
- (void)setInteger:(NSInteger)value forKey:(NSString *)defaultName;
- (void)setFloat:(float)value forKey:(NSString *)defaultName;
- (void)setDouble:(double)value forKey:(NSString *)defaultName;
- (void)setBool:(BOOL)value forKey:(NSString *)defaultName;
- (void)setURL:(nullable NSURL *)url forKey:(NSString *)defaultName NS_AVAILABLE(10_6, 4_0);讀取數(shù)據(jù)的方法:
- (nullable id)objectForKey:(NSString *)defaultName;
- (nullable NSString *)stringForKey:(NSString *)defaultName;
- (nullable NSArray *)arrayForKey:(NSString *)defaultName;
- (nullable NSDictionary<NSString *, id> *)dictionaryForKey:(NSString *)defaultName;
- (nullable NSData *)dataForKey:(NSString *)defaultName;
- (nullable NSArray<NSString *> *)stringArrayForKey:(NSString *)defaultName;
- (NSInteger)integerForKey:(NSString *)defaultName;
- (float)floatForKey:(NSString *)defaultName;
- (double)doubleForKey:(NSString *)defaultName;
- (BOOL)boolForKey:(NSString *)defaultName;
- (nullable NSURL *)URLForKey:(NSString *)defaultName NS_AVAILABLE(10_6, 4_0);刪除數(shù)據(jù)的方法:
- (void)removeObjectForKey:(NSString *)defaultName;保存數(shù)據(jù):
// 如果不手動(dòng)調(diào)用,系統(tǒng)會(huì)自動(dòng)保存,但時(shí)間不定
- (BOOL)synchronize;-
使用方法
//1.獲得NSUserDefaults文件 NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; //2.向文件中寫入內(nèi)容 [userDefaults setObject:@"AAA" forKey:@"a"]; [userDefaults setBool:YES forKey:@"sex"]; [userDefaults setInteger:21 forKey:@"age"]; //2.1立即同步 [userDefaults synchronize]; //3.讀取文件 NSString *name = [userDefaults objectForKey:@"a"]; BOOL sex = [userDefaults boolForKey:@"sex"]; NSInteger age = [userDefaults integerForKey:@"age"]; -
存儲(chǔ)id類型數(shù)據(jù)
+ (void)setValue:(id)value andKey:(NSString *)key { NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; [userDefaults setObject:value forKey:key]; [userDefaults synchronize]; } // 獲取數(shù)據(jù) + (NSString *)getValueByKey:(NSString *)key { NSUserDefaults * settings = [NSUserDefaults standardUserDefaults]; NSString *value = [settings objectForKey:key]; return value; }
注意:
- 偏好設(shè)置是專門用來(lái)保存應(yīng)用程序的配置信息的,一般不要在偏好設(shè)置中保存其他數(shù)據(jù)。
- 如果沒(méi)有調(diào)用synchronize方法,系統(tǒng)會(huì)根據(jù)I/O情況不定時(shí)刻地保存到文件中。所以如果需要立即寫入文件的就必須調(diào)用synchronize方法。
- 偏好設(shè)置會(huì)將所有數(shù)據(jù)保存到同一個(gè)文件中。即preference目錄下的一個(gè)以此應(yīng)用包名來(lái)命名的plist文件。
歡迎閱讀下一篇:
iOS-Ant-Bang互助社區(qū) 426981364
iOS技術(shù)交流群 461069757 歡迎加入!