如何正确的写入和读取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文件即可

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容