Plist 保存用户的配置数据
1.创建Plist文件,用Dictionary 读出数据
//获取沙盒目录
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path=[paths objectAtIndex:0];
//得到完整的文件名称
NSString *filepath = [path stringByAppendingString:@"/people.plist"];
//创建 Dictionary 对象
NSDictionary *dic = @{@"age":@18,@"name":@"jack"};
//将字典写入plist文件
[dic writeToFile:filepath atomically:YES];
//根据文件得到Dictionary 对象
NSDictionary *getDic = [NSDictionarydictionaryWithContentsOfFile:filepath];
NSLog(@"path:%@,数据:%@",filepath,getDic);
打印结果
2016-04-17 10:51:40.078 Plist_01[7370:546065] path:/Users/yefeng/Library/Developer/CoreSimulator/Devices/43183B3B-C46A-42E2-8605-538049FE5A42/data/Containers/Data/Application/FDEB9A5F-5860-423C-ADF6-3BC4494BB71B/Documents/people.plist,数据:{
age = 18;
name = jack;
}
2.简单封装PListTool,以及调用
创建PListTool文件
.h文件
//得到数据
-(NSMutableArray *) getAllData;
//插入数据
-(void) addNewDataWith:(NSString *) data;
//删除数据
-(void) deleteDataWith:(NSString *) data;
.m文件
#import "PListTool.h"
@implementation PListTool
-(NSString *)getFileName{
//获取沙盒路径
NSArray *paths= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *plistpath=[paths objectAtIndex:0];
NSString *fileName = [plistpath stringByAppendingString:@"/data.plist"];
//检查文件是否存在,不存在创建文件
NSFileManager *manager=[NSFileManagerdefaultManager];
if (![manager fileExistsAtPath:fileName])
{
[manager createFileAtPath:fileName contents:nilattributes:nil];
}
NSLog(@"%@",fileName);
return fileName;
}
-(NSMutableArray *) getAllData{
NSMutableArray *getArray = [[NSMutableArrayalloc] initWithContentsOfFile:[selfgetFileName]];
if (getArray == nil){
getArray =[NSMutableArrayarray];
return getArray;
}
else
{
return getArray;
}
}
-(void) addNewDataWith:(NSString *)data{
NSMutableArray *tmpArray = [NSMutableArrayarray];
tmpArray = [selfgetAllData];
[tmpArray addObject:data];
[tmpArray writeToFile:[selfgetFileName] atomically:YES];
}
-(void) deleteDataWith:(NSString *)data{
NSMutableArray *tmpArray = [NSMutableArrayarray];
tmpArray = [selfgetAllData];
[tmpArray removeObject:data];
[tmpArray writeToFile:[selfgetFileName] atomically:YES];
}
@end
文件的调用
#import "PListTool.h"
@implementation ViewController
- (void)viewDidLoad {
[superviewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSArray *array = [NSArrayarray];
PListTool *plist= [[PListToolalloc] init];
[plist addNewDataWith:@"123"];
array = [plist getAllData];
NSLog(@"%@",array);
}
日志如下
2016-04-18 06:46:58.709 plist_02[8218:579647] /Users/yefeng/Library/Developer/CoreSimulator/Devices/43183B3B-C46A-42E2-8605-538049FE5A42/data/Containers/Data/Application/E10AC86E-F8F8-429A-8CDD-55FEC923190C/Documents/data.plist
2016-04-18 06:46:58.709 plist_02[8218:579647] (
123,
123
)