? ? iOS的數(shù)據(jù)持久化存儲(chǔ)有很多種方式,最近做內(nèi)購(gòu)相關(guān)的東西,想把一些異常訂單信息和未處理訂單信息存儲(chǔ)起來(lái),由于要存儲(chǔ)數(shù)組,所以想到用plist文件做數(shù)據(jù)持久化存儲(chǔ)。
1,如何創(chuàng)建一個(gè)plist文件
當(dāng)創(chuàng)建plist文件時(shí),這里有一個(gè)點(diǎn)需要特別注意,不能用[NSBundle mainBundle]的目錄下進(jìn)行創(chuàng)建,寫(xiě)入文件,因?yàn)閎undle目錄是只讀的!
創(chuàng)建代碼如下:
NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"ValidatePayProducts.plist"];
if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {// 文件不存在
[[NSFileManager defaultManager] createFileAtPath:path contents:nil attributes:nil];
// 寫(xiě)入一個(gè)數(shù)組
NSMutableArray *arr=[[NSMutableArray alloc] init];
[arr writeToFile:path atomically:YES];
}
由于plist文件的root只能是數(shù)組或者字典,這里用數(shù)組
2,讀取plist,修改
//首先判斷路
NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"ValidatePayProducts.plist"];
if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {// 文件存在
// 讀取文件 ? ?
NSMutableArray *payarr = [NSMutableArray arrayWithContentsOfFile:path];
// 對(duì)數(shù)組做操作,并重新寫(xiě)入plist文件即可
}