Search code examples
ioscocoa-touchnsarrayplist

can't write data to .plist in iOS


I'm trying to write data to .plist file with next method:

-(IBAction)saveCity:(id)sender{
    NSString * path = [[NSBundle mainBundle] pathForResource:@"propTest" ofType:@"plist"];
    NSMutableArray * array = [NSMutableArray arrayWithContentsOfFile:path];
    [ array addObject:@"addedTest"];
    if ([array writeToFile:path atomically:NO]){
        NSLog(@"written");
    }
}

I have created propTest.plist in advance manually with next content:

enter image description here

After invoking saveCity: several times I can see that array which I read from propTest.plist contains my strings:

enter image description here

But actually it contains only what I added manually:

enter image description here

Could you please help me to find a reason why new Strings are not added to .plist permanently ?


Solution

  • Simple answer is - No, you cannot do this. iOS application run in sandbox environment wherein you cannot modify the application bundle at run time and therefore you cannot write anything inside [NSBundle mainBundle].

    You should use application's documents directory instead. This is how you can do this. Here, just for your knowledge sake, I am copying data from main bundle, appending new details and writing back to documents directory.

    // Get you plist from main bundle
    NSString *path = [[NSBundle mainBundle] pathForResource:@"propTest" ofType:@"plist"];
    NSMutableArray *array = [NSMutableArray arrayWithContentsOfFile:path];
    
    // Add your object
    [array addObject:@"addedTest"];
    
    // Get Documents directory path
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *plistLocation = [documentsDirectory stringByAppendingPathComponent:@"propTest.plist"];
    
    // Write back to Documents directory
    [array writeToFile:plistLocation atomically:YES];