将plist复制到文档目录

时间:2011-10-07 22:14:14

标签: iphone objective-c ipad

如何将app build中的现有plist复制到Document目录?

我的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

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

2 个答案:

答案 0 :(得分: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]);
    }

}

答案 1 :(得分:0)

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