數(shù)據(jù)持久化方案二----plist

寫在前方 筆者會(huì)用到之前文章的方法(自己封裝下)

一、plist是Xcode的一種資源包,可以用來作為存儲(chǔ)工具,是一種很直觀的可視化文件。它是按一級(jí)級(jí)節(jié)點(diǎn)組成的,根節(jié)點(diǎn)是個(gè)Array或者Dictionary。

如:
0.png

二、支持的存儲(chǔ)數(shù)據(jù)類型

NSArray(含NSMutableArray)、NSDictionary(含NSMutableDictionary)、NSData(含NSMutableData)、NSString(含NSMutableString)、NSNumber、NSDate、BOOL。同樣,存儲(chǔ)的對(duì)象全是不可變的。

三、創(chuàng)建方式
1、工程里手動(dòng)創(chuàng)建(只讀的,不能用代碼寫入),
如:


image.png

2、沙盒中創(chuàng)建(可讀可寫)
如:


image.png

四、相關(guān)代碼
(一)、工程里手動(dòng)創(chuàng)建的plist文件
1、存數(shù)據(jù)
按照需求,根據(jù)數(shù)組或者字段手動(dòng)填入數(shù)據(jù)。

2、讀文件

 NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"XLTest" ofType:@"plist”];

3、讀數(shù)據(jù)
<1>、根節(jié)點(diǎn)是字典

 NSDictionary *aimDic = [NSDictionary dictionaryWithContentsOfFile:plistPath];
 NSLog(@"plist :%@",aimDic);

<2>、根節(jié)點(diǎn)是數(shù)組

 NSArray *aimArr = [NSArray arrayWithContentsOfFile:plistPath];
 NSLog(@"plist :%@",aimArr);

(二)、在沙盒里代碼創(chuàng)建的plist文件
1、創(chuàng)建文件

NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *plistPath = [docPath stringByAppendingPathComponent:@"myFile/test.plist"];
//見"寫在前方"
[XLFileManagerTool creatFileWithPath:plistPath];

2、存數(shù)據(jù)

NSMutableDictionary *rootDic = [NSMutableDictionary new];
rootDic[@"key1"] = @"name";
NSArray *ageArr = @[@1, @2, @YES];
rootDic[@"key2"] = ageArr;
[rootDic writeToFile:plistPath atomically:YES];

3、讀文件數(shù)據(jù)
<1>、根節(jié)點(diǎn)是字典

 NSDictionary *aimDic = [NSDictionary dictionaryWithContentsOfFile:plistPath];
 NSLog(@"plist :%@",aimDic);

<2>、根節(jié)點(diǎn)是數(shù)組
NSArray *aimArr = [NSArray arrayWithContentsOfFile:plistPath];
NSLog(@"plist :%@",aimArr);

4、修改數(shù)據(jù)
根據(jù)節(jié)點(diǎn),按需求,從根節(jié)點(diǎn)重寫write。
如:

NSArray *aimArr = @[@1, @2];
[aimArr writeToFile:plistPath atomically:YES];

5、刪除數(shù)據(jù)
在對(duì)應(yīng)節(jié)點(diǎn)刪,然后重寫放回節(jié)點(diǎn),write進(jìn)去
如在根節(jié)點(diǎn)清空根字典:

NSDictionary *aimD = @{};
[aimD writeToFile:plistPath atomically:YES];

6、刪除plist
按照前文中的文件操作即可

如:

[XLFileManagerTool removeFileOfPath:plistPath];  
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容