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

时间:2011-11-01 16:15:44

标签: 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文件中。

2 个答案:

答案 0 :(得分:2)

您无法写入您的捆绑包,它是只读的。如果是你的情况,你写的是相对路径,而不是捆绑。

我不确定iOS应用的默认工作目录是什么。最好使用绝对路径。您应该写入documents / cache目录。这样的事情会为你找到路径:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 

然后只需抓住lastObject并将其添加到您的文件名中。

答案 1 :(得分:1)

正如@logancautrell所提到的,你不能在mainbundle中写,你可以将你的plist保存在app documents文件夹中,你可以这样做:

 NSString *path = @"example.plist";
 NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
 NSString *basePath = ([paths count]> 0)? [paths objectAtIndex: 0]: nil;
 NSString *documentPath = [basePath stringByAppendingPathComponent:path] // Documents
 NSFileManager *fileManager  = [NSFileManager defaultManager];
 BOOL checkfile = [fileManager fileExistsAtPath: documentPath];
 NSLog(@"%@", (checkFile ? @"Exist": @"Not exist"));//check if exist
 if(!checkfile) {//if not exist
    BOOL copyFileToDoc = [yourDictionary writeToFile:documentPath atomically: YES];
    NSLog(@"%@",(copyFileToDoc ? @"Copied": @"Not copied"));
  }
相关问题