Reputation: 5972
In my app I have a table view where the user presses an "add" button in the nav bar and a new cell is added to the table view. The data from the table is loaded from an NSArray and each index in the array is storing an NSMutableDictionary with 4 Key-Value pairs. This array is saved to a .plist every time a cell is added. Now when the user selects a row in the table a detail view gets loaded. This detail view simply loads the data from the saved .plist depending on what row was selected.
In this detail view I want to allow the user to edit the data in the dictionary for that specific row. I've been trying different things and I can read the data from the dictionary and load it into the view but when I try and save the data back to the dictionary my app keeps terminating.
Can someone explain to me the proper way to reading and writing data to a an NSMutableDictionary?
This is how i'm writing the data back to the .plist:
NSMutableArray *array = [[NSMutableArray alloc] initWithContentsOfFile:filePath];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
dict = [array objectAtIndex:selectedRow];
NSString *tempA = [[NSString alloc] initWithFormat:@"%d pts", ivar_A];
NSString *tempB = [[NSString alloc] initWithFormat:@"%d pts", ivar_B];
NSString *tempC = [[NSString alloc] initWithFormat:@"%d pts", ivar_C];
[dict setValue:tempA forKey:@"keyA"];
[dict setValue:tempB forKey:@"keyB"];
[dict setValue:tempC forKey:@"keyC"];
[tempA release];
[tempB release];
[tempC release];
[array insertObject:dict atIndex:selectedRow];
//Save the modified array back to the plist
[array writeToFile:[self dataFilePath] atomically:YES];
[dict release];
[array release];
Upvotes: 1
Views: 1258
Reputation: 11502
if you use [[NSMutableDictionary alloc] dictionaryFromContentsOfFile:@"pathtofile.plist], the contents of the dictionary will still be immutable, even if the top level container is mutable. It is specifically stated in Apple's reference.
The dictionary representation in the file identified by path must contain only property list objects (NSString, NSData, NSDate, NSNumber, NSArray, or NSDictionary objects). For more details, see Property List Programming Guide. The objects contained by this dictionary are immutable, even if the dictionary is mutable.
If you need to make the data structure writable again, you will need to make a copy of the loaded data structure using mutable types, like
[NSMutableDictionary dictionaryWithDictionary:oOrig]
etc.
Upvotes: 3