在开发过程中,有时候需要把程序的一些配置保存下来,或者游戏数据等等。 这时候需要写入Plist数据。
写入的plist文件会生成在对应程序的沙盒目录里。
接着上面读取plist数据的代码,加入了写入数据的代码。
// 文件保存的地址分两种
// 1、获取应用程序沙盒下的Documents目录(或其它目录)
NSArray *pathArr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *path = [pathArr objectAtIndex:0];
//得到完整的文件名
NSString *filePath = [path stringByAppendingPathComponent:@"test.plist"];
// 2、[NSBundle mainBundle]
// NSString *filePath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"plist"];
NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
NSLog(@"%@", data);
// 添加一项内容
[data setObject:@"add some content" forKey:@"c_key"];
// 文件写入
if ([data writeToFile:filePath atomically:YES]) {
NSLog(@"写入成功");
} else {
NSLog(@"写入失败");
}
// 那怎么证明我的数据写入了呢?读出来看看
// 文件读取
NSMutableDictionary *data1 = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
NSLog(@"%@", data1);