2011-10-07 126 views
3

如何将现有的plist复制到文档目录中?将plist复制到文档目录

我的plist基本上是字典的数组,我已经成功plist中使用以下复制到该目录:

BOOL success; 
      NSError *error; 

      NSFileManager *fileManager = [NSFileManager defaultManager]; 
      NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
      NSString *documentsDirectory = [paths objectAtIndex:0]; 
      NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"States.plist"]; 

      success = [fileManager fileExistsAtPath:filePath]; 
      if (success) return; 

      NSString *path = [[NSBundle mainBundle] pathForResource:@"States" ofType:@"plist"];  
      success = [fileManager copyItemAtPath:path toPath:filePath error:&error]; 

      if (!success) { 
       NSAssert1(0, @"Failed to copy Plist. Error %@", [error localizedDescription]); 
      } 

然而,当我试图访问NSDictionary中它给了我:

CoreAnimation: ignoring exception: -[__NSCFDictionary setObject:forKey:]: mutating method sent to immutable object 

这是为什么?我必须重新启动应用程序,现在我可以更改存储在我的阵列中的字典

回答

0

只需在文档目录中创建一个新的pList,并将其设置为您现有的plist的内容。

+0

我想先复制它,因为现在我已经在我的应用程序包中。如果您要说先创建它,那么如何在文档目录中创建它?从发现者手动执行它?如果是在电话上呢? – xonegirlz

+0

在您的应用程序包中放置一个空plist,然后复制现有的plist。如果这不起作用,那么你需要审查你的设计决定。如果您向我提供更多关于您的需求/实施情况的信息,我可以帮助您。 – darksky

+0

我希望能够将它重新写回plist,因此这就是为什么我要避免使用应用程序包。我正在考虑将plist复制到文档目录,以便我可以在那里再次写入 – xonegirlz

5

这是我将* .plist文件复制到文档文件夹的方式。希望这可以帮助。

+ (NSString*) getPlistPath:(NSString*) filename{ 
    //Search for standard documents using NSSearchPathForDirectoriesInDomains 
    //First Param = Searching the documents directory 
    //Second Param = Searching the Users directory and not the System 
    //Expand any tildes and identify home directories. 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES); 
    NSString *documentsDir = [paths objectAtIndex:0]; 
    return [documentsDir stringByAppendingPathComponent:filename]; 
} 
+ (void) copyPlistFileToDocument{ 
    NSFileManager *fileManager = [NSFileManager defaultManager]; 
    NSError *error; 
    NSString *dbPath = [Utilities getPlistPath:@"AppStatus.plist"]; 
    if(![fileManager fileExistsAtPath:dbPath]) 
    { 
     NSString *defaultDBPath = [[NSBundle mainBundle] pathForResource:@"AppStatus" ofType:@"plist"]; 
      BOOL copyResult = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error]; 
      if(!copyResult) 
        NSAssert1(0, @"Failed to create writable plist file with message '%@'.", [error localizedDescription]); 
    } 

}