Add plist dictionary to favourites tab (TableView), using XCode 4
-
20-06-2021 - |
Question
I use a plist containing of an array of dictionaries to fill a MainTableViewController through a MutableArray. When a cell is chosen, the reprecented dictionary are passed to the DetailViewController, where the values from the strings in the reprecented dictionary are displayed. I've added a button to the DetailView in the storyboard, and I want this button to send the reprecented dictionary to the Favorites tab, which is called FavoritesTableViewController. I'm thinking of ways to do it but I'm new to programming so I have to ask for advice.
I've come up with two possible ways of doing it. I may be far away from the right answer, but at least I'm trying to think.
1: The button changes a boolean to yes in the reprecented dictionary, and the prototype cell in the FavoritesViewController are told to display the dictionaries with boolean=yes.
2: The button copies the dictionary to a new plist with favourites, displayed in the favourites tableview.
But I really have no idea..
EDIT:
Code so far in the DetailViewController:
-(IBAction)FavoriteButton:(id)sender
{
[[NSNotificationCenter defaultCenter] postNotificationName:@"ItemSelected"
object:selectedObject];
}
Code so far to display the wines in the FavoritesViewController:
[[NSNotificationCenter defaultCenter] addObserverForName:@"ItemSelected"
object:nil
queue:[NSOperationQueue mainQueue]
usingBlock:^(NSNotification* notif) {
[favoritedObjects release];
favoritedObjects = [[notif object] retain];
[self.tableView reloadData];
}];
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [favoritedObjects count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Favcell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// Configure the cell...
NSString *cellValue = [favoritedObjects valueForKey:@"Name"];
cell.textlabel.text = cellValue;
return cell;
}
This shows 20 cells with the value from the Key: "Name" from the last Object in the DetailViewController I pressed "Add to Favorites" button for. For example if I add "Gato Negro" to favorites, it displays "Gato Negro" in 20 cells. if I then add "Luna" to fav, it displays "Luna" in the 20 cells in FavoritesViewController.
Solution
How about posting a notification and passing the selected dictionary as the object
or userInfo
?
[[NSNotificationCenter defaultCenter] postNotificationName:@"ItemSelected"
object:mySelectedDictionary];
In the FavoritesViewController
you just subscribe to this notification (e.g. in the init
method) like this:
[[NSNotificationCenter defaultCenter] addObserverForName:@"ItemSelected"
object:nil
queue:[NSOperationQueue mainQueue]
usingBlock:^(NSNotification* notif) {
[dictionaryToShow release];
dictionaryToShow = [[notif object] retain];
[self.tableView reloadData];
}];