无法将数据写入 iOS 中的 .plist
can't write data to .plist in iOS
我正在尝试使用下一个方法将数据写入 .plist 文件:
-(IBAction)saveCity:(id)sender{
NSString * path = [[NSBundle mainBundle] pathForResource:@"propTest" ofType:@"plist"];
NSMutableArray * array = [NSMutableArray arrayWithContentsOfFile:path];
[ array addObject:@"addedTest"];
if ([array writeToFile:path atomically:NO]){
NSLog(@"written");
}
}
我已经提前手动创建了propTest.plist,接下来的内容是:
在多次调用 saveCity: 之后,我可以看到我从 propTest.plist 中读取的数组包含我的字符串:
但实际上它只包含我手动添加的内容:
你能帮我找出新字符串没有永久添加到 .plist 的原因吗?
简单的答案是 - 不,你不能这样做。 iOS 沙盒环境中的应用程序 运行,您无法在 运行 时修改应用程序包,因此您无法在 [NSBundle mainBundle]
.
中写入任何内容
您应该改用应用程序的文档目录。这就是你如何做到这一点。在这里,为了您的知识起见,我从主包中复制数据,附加新的详细信息并写回文档目录。
// Get you plist from main bundle
NSString *path = [[NSBundle mainBundle] pathForResource:@"propTest" ofType:@"plist"];
NSMutableArray *array = [NSMutableArray arrayWithContentsOfFile:path];
// Add your object
[array addObject:@"addedTest"];
// Get Documents directory path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *plistLocation = [documentsDirectory stringByAppendingPathComponent:@"propTest.plist"];
// Write back to Documents directory
[array writeToFile:plistLocation atomically:YES];
我正在尝试使用下一个方法将数据写入 .plist 文件:
-(IBAction)saveCity:(id)sender{
NSString * path = [[NSBundle mainBundle] pathForResource:@"propTest" ofType:@"plist"];
NSMutableArray * array = [NSMutableArray arrayWithContentsOfFile:path];
[ array addObject:@"addedTest"];
if ([array writeToFile:path atomically:NO]){
NSLog(@"written");
}
}
我已经提前手动创建了propTest.plist,接下来的内容是:
在多次调用 saveCity: 之后,我可以看到我从 propTest.plist 中读取的数组包含我的字符串:
但实际上它只包含我手动添加的内容:
你能帮我找出新字符串没有永久添加到 .plist 的原因吗?
简单的答案是 - 不,你不能这样做。 iOS 沙盒环境中的应用程序 运行,您无法在 运行 时修改应用程序包,因此您无法在 [NSBundle mainBundle]
.
您应该改用应用程序的文档目录。这就是你如何做到这一点。在这里,为了您的知识起见,我从主包中复制数据,附加新的详细信息并写回文档目录。
// Get you plist from main bundle
NSString *path = [[NSBundle mainBundle] pathForResource:@"propTest" ofType:@"plist"];
NSMutableArray *array = [NSMutableArray arrayWithContentsOfFile:path];
// Add your object
[array addObject:@"addedTest"];
// Get Documents directory path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *plistLocation = [documentsDirectory stringByAppendingPathComponent:@"propTest.plist"];
// Write back to Documents directory
[array writeToFile:plistLocation atomically:YES];