首先在视图上创建两个button,分别是保存数据和读取数据,对应连线。
/**
* 点击保存按钮
*/
- (IBAction)saveDataBtnClick:(id)sender {
//获取应用沙盒目录
NSString * home = NSHomeDirectory();
//NSUserDomainMask 在用户目录下查找
//YES 代表用户目录的~
//NSDocumentDirectory 查找Documents文件夹
NSString * doc = [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory,NSUserDomainMask,YES) lastObject];
NSString * path = [doc stringByAppendingPathComponent:@"abc.plist"];
NSLog(@"%@",path);
NSDictionary * dic = @{@"name",:@"su",@"age":@"21"};
//调用writeTOFile将数据写入文件
[dict writeToFile:path atomically:YES];
/*
plist只能存储系统自带的一些常规的类,也就是有writeTOFile方法的对象才可以使用plist保存数据
字符串/字典/数据/NSNumber/NSData....
*/
}
/**
*点击读取按钮
*/
- (IBAction)readDataBtnClick:(id)sender {
NSString * doc = [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory,NSUserDomainMask, YES) lastObject];
NSString * path = [doc stringByAppendingPathComponent:@"abc.plist"];
//读取数据 dictionaryContentsOfFile
NSDictionary * dic = [NSDictionary dictionaryContentsOfFile:path];
NSLog(@"%@",dict);
}