I’m using a plist with structure like this: plist, array, dict key string key string /dict, dict key string key string /dict, /array, /plist.
What I want with the following code it to set the “Done” string’s value in current dictionary to “Yes”.
But now, the code replaces the whole array of dictionaries with the strings of the current dictionary (with the “Done” key valued “Yes” as it should, though.)
What would be the correct code for what I want?
in DetailViewController.m:
-(IBAction)favoriteButtonPressed:(id)sender
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"Object.plist"];
[[detailsDataSource objectAtIndex: detailIndex] setValue:@"Yes" forKey:@"Done"];
[[detailsDataSource objectAtIndex: detailIndex] writeToFile:path atomically:YES];
}
The detailsDataSource and detailIndex are recieved from TableViewController.m segue if that matters.
TableViewController.m segue part:
detailViewController.detailsDataSource = [[NSArray alloc]initWithArray:objectsArray];
detailViewController.detailIndex = selectedRowIndex.row;
DetailViewController viewDidLoad
if ([[[detailsDataSource objectAtIndex: detailIndex] valueForKey:@"Favorite"] isEqual:@"Yes"]) {
[favoriteButton setImage:[UIImage imageNamed:@"favoritedItem.png"] forState:UIControlStateSelected | UIControlStateHighlighted];
}
districtLabel.text = [[detailsDataSource objectAtIndex: detailIndex] valueForKey:@"District"];
detailsDataSource array is used like this in detailViewController so I cannot change from array to dictionary, must make a mutable copy in that case.
setValue:forKeyis not for modifying mutable dictionaries. You should usesetObject:forKey. I.e., this:Should be:
If that doesn’t fix the problem, make sure the dictionary and array are both mutable:
Also, instead of
@"Yes", you can use[NSNumber numberWithBool:YES]:[mutDict setObject:[NSNumber numberWithBool:YES] forKey:@"Done"];would generally be better form then using
@"Yes".And:
Should be:
Also noticed that you may have a memory leak with:
Make sure to autorelease when using property setters that retain.