简体   繁体   English

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

[英]How can I overwrite the contents of a plist file? (iPhone / iPad)

I have a plist file in my main app bundle that I want to update via my app. 我的主应用程序包中有一个plist文件,我想通过我的应用程序进行更新。 Here is the code I'm using, the problem is that the plist doesn't seem to be getting updated. 这是我正在使用的代码,问题是plist似乎没有更新。 Is my code incorrect or is there another issue? 我的代码不正确还是还有其他问题?

// 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];

Please can someone help me out? 有人可以帮我吗?

IOS restricts writing to bundled files. IOS限制写入捆绑文件。 If you want a writable plist, you need to copy it to your app's Documents folder and write to it there. 如果您想要一个可写的plist,则需要将其复制到应用程序的Documents文件夹中并在其中写入。

Here's how I'm doing it in one of my apps 这是我在其中一个应用程序中的操作方法

//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;
}

Hope this helps 希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM