我一直在尝试将数据写回到我的包中预定义的 plist 文件 (data.plist)。使用下面的代码,我调用例程“dictionaryFromPlist”来打开文件,然后调用“writeDictionaryToPlist”来写入 plist 文件。但是,没有数据添加到 plist 文件中。
NSDictionary *dict = [self dictionaryFromPlist];
NSString *key = @"Reports";
NSString *value = @"TestingTesting";
[dict setValue:value forKey:key];
[self writeDictionaryToPlist:dict];
- (NSMutableDictionary*)dictionaryFromPlist {
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"plist"];
NSMutableDictionary* propertyListValues = [[NSMutableDictionary alloc]
initWithContentsOfFile:filePath];
return [propertyListValues autorelease];
}
- (BOOL)writeDictionaryToPlist:(NSDictionary*)plistDict{
NSString *filePath = @"data.plist";
BOOL result = [plistDict writeToFile:filePath atomically:YES];
return result;
}
代码成功运行,没有抛出错误,但没有数据添加到我的 plist 文件中。
最佳答案
您无法写入您的包,它是只读的。如果你的情况如此,你正在写入相对路径,而不是 bundle 。
我不确定 iOS 应用程序的默认工作目录是什么。最好使用绝对路径。您应该写入 Documents/cache 目录。像这样的东西将为您找到路径:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
然后只需获取最后一个对象并将其添加到您的文件名中即可。
关于xcode - 将数据添加到 plist 文件时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7969432/