Brett Gregson
Brett Gregson

Reputation: 5913

iOS - saving to a plist

I am trying to change the value of a plist (@key "userId" which has a starting value of 0)

NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"GlobalSettings" ofType:@"plist"];
NSMutableDictionary *data = [NSMutableDictionary dictionaryWithContentsOfFile:plistPath];
NSDictionary *userId = [data objectForKey:@"userId"];

[data setValue:(@"99") forKey:@"userId"];
[data writeToFile:plistPath atomically: NO];

userId = [data objectForKey:@"userId"];
NSLog(@"%@", userId); 

The log shows that the value has change to 99, but when I open the plist the value is still 0

Upvotes: 0

Views: 279

Answers (1)

Paresh Navadiya
Paresh Navadiya

Reputation: 38239

You cannot save data in application's main bundle instead you have to do in document directory like this:

 NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *plistFilePath = [documentsDirectory stringByAppendingPathComponent:@"GlobalSettings.plist"];

if([[NSFileManager defaultManager] fileExistsAtPAth:plistFilePath]) 
{//already exits

   NSMutableDictionary *data = [NSMutableDictionary dictionaryWithContentsOfFile:plistFilePath];
   NSDictionary *userId = [data objectForKey:@"userId"];
   [data setValue:(@"99") forKey:@"userId"]; //new value here
   [data writeToFile:plistPath atomically: YES];
   userId = [data objectForKey:@"userId"];
   NSLog(@"%@", userId); 
}
else{ //firstly take content from plist and then write file document directory 

 NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"GlobalSettings" ofType:@"plist"];
 NSMutableDictionary *data = [NSMutableDictionary dictionaryWithContentsOfFile:plistPath];
 NSDictionary *userId = [data objectForKey:@"userId"];

 [data setValue:(@"99") forKey:@"userId"];//new value here
 [data writeToFile:plistFilePath atomically:YES];

 userId = [data objectForKey:@"userId"];
 NSLog(@"%@", userId); 
}

Upvotes: 4

Related Questions