如何覆盖plist文件的内容? (iPhone / iPad)

时间:2012-01-21 17:08:07

标签: iphone objective-c ios plist

我的主应用程序包中有一个plist文件,我想通过我的应用程序更新。这是我正在使用的代码,问题是plist似乎没有得到更新。我的代码不正确还是有其他问题?

// Data
NSMutableDictionary *data = [[NSMutableDictionary alloc] init];
[data setObject:self.someValue forKey:@"Root"];

// Save the logs
NSString *filepath = [[NSBundle mainBundle] pathForResource:@"MyFile" ofType:@"plist"];
[data writeToFile:filepath atomically:YES];

有人可以帮帮我吗?

2 个答案:

答案 0 :(得分:3)

IOS限制写入捆绑文件。如果你想要一个可写的plist,你需要将它复制到你的应用程序的Documents文件夹并在那里写入。

答案 1 :(得分:2)

以下是我在其中一个应用中的表现

//get file paths
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [documentPaths objectAtIndex:0];
NSString *documentPlistPath = [documentsDirectory stringByAppendingPathComponent:@"document.plist"];
NSString *bundlePath = [[NSBundle mainBundle] bundlePath];  
NSString *bundlePlistPath = [bundlePath stringByAppendingPathComponent:@"bundle.plist"];

//if file exists in the documents directory, get it
if([fileManager fileExistsAtPath:documentPlistPath]){            
    NSMutableDictionary *documentDict = [NSMutableDictionary dictionaryWithContentsOfFile:documentPlistPath];
        return documentDict;
} 
//if file does not exist, create it from existing plist
else {
    NSError *error;
    BOOL success = [fileManager copyItemAtPath:bundlePlistPath toPath:documentPlistPath error:&error];
    if (success) {
        NSMutableDictionary *documentDict = [NSMutableDictionary dictionaryWithContentsOfFile:documentPlistPath];
        return documentDict;
    }
    return nil;
}

希望这有帮助