- 创建plist文件路径(一般保存到沙盒document文件夹中)
//获取plist文件路径
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [path objectAtIndex:0];
NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"user_phone.plist"];
2.根据路径,创建或者取出plist文件内容(如果是数组用NSMutableArray去接,如果是字典就用NSMutableDictionary去接)
//比如说根容器是个数组(字典同理)
NSMutableArray * plistArray =nil;
if (![[NSMutableArray alloc]initWithContentsOfFile:plistPath]) {
//创建一个根容器为数组的plist文件
plistArray = [NSMutableArray array];
[plistArray writeToFile:plistPath atomically:YES];
}else{
plistArray = [[NSMutableArray alloc] initWithContentsOfFile:plistPath];
}
3.关于plsit文件的一些操作(其实就是操作数组或字典,然后写入plist)
- 添加一条数据(以添加账号密码为例)
NSMutableDictionary * newsDict = [NSMutableDictionary dictionary];
[newsDict setObject:@"1234567890" forKey:@"user_phone"];
[newsDict setObject:@"123" forKey:@"user_pass"];
[plistArray addObject:newsDict];
[plistArray writeToFile:plistPath atomically:YES];
- 修改一条数据
for (NSDictionary * dict in plistArray) {
if ([dict[@"user_phone"] isEqualToString:userPhone]) {
[dict setValue:userPass forKey:@"user_pass"];
[plistArray writeToFile:plistPath atomically:YES];
NSLog(@"%@",plistArray);
return;
}
}
- 删除一条数据
NSMutableArray * plistArray = [[NSMutableArray alloc] initWithContentsOfFile:plistPath];
for (int i = 0; i < plistArray.count; i++) {
NSDictionary * dict = plistArray[i];
if ([dict[@"user_phone"] isEqualToString:userPhone]) {
[plistArray removeObject:dict];
[plistArray writeToFile:plistPath atomically:YES];
}
}