xcode - 将数据添加到 plist 文件时出现问题

标签 xcode ios4 plist nsdictionary

我一直在尝试将数据写回到我的包中预定义的 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/

相关文章:

iphone - 核心动画xml或json框架

iphone - Plist 倒序

iphone - iPhone 中的存储

iphone - 使用 NSDictionary 对象写入 plist 文件

iphone - 如何在iphone sdk中监控pdf下载过程

ios - 如何导入常规(非库)xcode 项目?

xcode - 应用内截图并附加到电子邮件,无需保存到库中

mysql - 将 MySQL 模式作为 CoreData 数据模型导入 Xcode

ios - 实现TripAdvisor api的示例示例-iOS应用程序

ios - XCode 8 GM 种子 - 上传到 TestFlight 时出错