在iOS的开发中,用到plist的时候还是很多的,那到底怎么用呢?接下来我们进行介绍......
plist的创建:
创建完plist,你可以选择plist的数据是字典还是数组
2.plist的存取删:
存:
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"Data" ofType:@"plist"];
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *plistPath1 = [paths objectAtIndex:0];
//得到完整的文件名
NSString *filename=[plistPath1 stringByAppendingPathComponent:@"Data.plist"];
NSMutableArray * data_arr = [[NSMutableArray alloc]initWithContentsOfFile:filename];
if (!data_arr) {
data_arr = [[NSMutableArray alloc]initWithContentsOfFile:plistPath];
}else{
data_arr = [[NSMutableArray alloc]initWithContentsOfFile:filename];
}
NSLog(@"----dataArr--%@",data_arr);
NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
[dic setObject:time forKey:@"time"];
[dic setObject:sort forKey:@"sort"];
[dic setObject:price forKey:@"price"];
[data_arr addObject:dic];
//输入写入
[data_arr writeToFile:filename atomically:YES];
NSMutableArray *data1 = [[NSMutableArray alloc] initWithContentsOfFile:filename];
NSLog(@"data==%@",data1);
注意:在存数据的时候一定要先判断你拿到的data_arr对象到底存在不存在
取:
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *plistPath1 = [paths objectAtIndex:0];
//得到完整的文件名
NSString *filename=[plistPath1 stringByAppendingPathComponent:@"Data.plist"];
dataSource = [[NSMutableArray alloc] initWithContentsOfFile:filename];
删:
删除某一个元素:
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *plistPath1 = [paths objectAtIndex:0];
//得到完整的文件名
NSString *filename=[plistPath1 stringByAppendingPathComponent:@"caogao.plist"];
NSMutableArray * data_arr = [[NSMutableArray alloc]initWithContentsOfFile:filename];
[data_arr removeObjectAtIndex:self.index];
//输入写入
[data_arr writeToFile:filename atomically:YES];
NSMutableArray *data1 = [[NSMutableArray alloc] initWithContentsOfFile:filename];
NSLog(@"删除草稿后数据data==%@",data1);
删除所有的元素:
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *plistPath1 = [paths objectAtIndex:0];
//得到完整的文件名
NSString *filename=[plistPath1 stringByAppendingPathComponent:@"caogao.plist"];
NSMutableArray * data_arr = [[NSMutableArray alloc]initWithContentsOfFile:filename];
[data_arr removeAllObjects];
//输入写入
[data_arr writeToFile:filename atomically:YES];
NSMutableArray *data1 = [[NSMutableArray alloc] initWithContentsOfFile:filename];
NSLog(@"删除草稿后数据data==%@",data1);