Search code examples
iosnsstringnsdictionarynsbundle

Override an existed Property List


I want to override a Property List with a specific Dictionary.

        NSDictionary *plist = [[NSDictionary alloc]initWithContentsOfURL:url];

        NSString *path = [[NSBundle mainBundle] pathForResource:@"Routes" ofType:@"plist"];

        NSMutableDictionary *lastDict = [[NSMutableDictionary alloc] initWithContentsOfFile:path];

        [lastDict setValue:[plist objectForKey:@"Routes"] forKey:@"Routes"];

        [lastDict writeToFile:path atomically:YES];

PS: plist (dictionary is OK) but after writeToFile method, nothing happend with my Property List from the path ...


Solution

  • Files added to the main bundle cannot be modified (they are supposed to be completely static), that's the reason why the code will load the plist file but won't be able do overwrite it.

    You are not actually noticing that the write operation is failing because you are not checking its result. (- writeToFile:atomically: actually returns a BOOL that tells you whether the operation was completed successfully or not.)

    If you want to have a plist file that you can dynamically edit, you should add it to the document folder of your app. Here some sample code to show the basics of how it is possible to create and edit a plist file inside Documents.

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
    NSString *plistPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"simple.plist"];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    BOOL fileExists = [fileManager fileExistsAtPath:plistPath];
    if (!fileExists) {
        // The plist file does not exist yet so you have to create it
        NSLog(@"The .plist file exists");
    
        // Create a dictionary that represents the data you want to save
        NSDictionary *plist = @{ @"key": @"value" };
    
        // Write the dictionary to disk
        [plist writeToFile:plistPath atomically:YES];
    
        NSLog(@"%@", plist);
    } else {
        // The .plist file exists so you can do interesting stuff
        NSLog(@"The .plist file exists");
    
        // Start by loading it into memory
        NSMutableDictionary *plist = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
    
        NSLog(@"%@", plist);
    
        // Edit something
        [plist setValue:@"something" forKey:@"key"];
    
        // Save it back
        [plist writeToFile:plistPath atomically:YES];
    
        NSLog(@"%@", plist);
    }
    

    I hope this helps!