简体   繁体   中英

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. Here is the code I'm using, the problem is that the plist doesn't seem to be getting updated. 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. If you want a writable plist, you need to copy it to your app's Documents folder and write to it there.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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