Yuriy Vasylenko
Yuriy Vasylenko

Reputation: 3151

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 ?

Upvotes: 1

Views: 381

Answers (1)

Abhinav
Abhinav

Reputation: 38162

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

Upvotes: 2

Related Questions