如何正确的写入和读取plist文件

    iOS的数据持久化存储有很多种方式,最近做内购相关的东西,想把一些异常订单信息和未处理订单信息存储起来,由于要存储数组,所以想到用plist文件做数据持久化存储。

1,如何创建一个plist文件

当创建plist文件时,这里有一个点需要特别注意,不能用[NSBundle mainBundle]的目录下进行创建,写入文件,因为bundle目录是只读的!

创建代码如下:

NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"ValidatePayProducts.plist"];

if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {// 文件不存在

[[NSFileManager defaultManager] createFileAtPath:path contents:nil attributes:nil];

// 写入一个数组

NSMutableArray *arr=[[NSMutableArray alloc] init];

[arr writeToFile:path atomically:YES];

}

由于plist文件的root只能是数组或者字典,这里用数组

2,读取plist,修改

//首先判断路

NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"ValidatePayProducts.plist"];

if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {// 文件存在

// 读取文件    

NSMutableArray *payarr = [NSMutableArray arrayWithContentsOfFile:path];

// 对数组做操作,并重新写入plist文件即可

}

你可能感兴趣的:(如何正确的写入和读取plist文件)