Reputation: 895
I'm working on an app that has a shopping cart. When I add a product in my shopping cart, my button segues to a table view controller modally. Then when I select a row, the modal view controller should be dismissed. I tried to implement this using my delegate. Here's my code:
(irrelevant code omitted)
ItemsTableViewController (the list of products to choose from)
//the header file
@class ItemsTableViewController;
@protocol ItemsTableViewControllerDelegate <NSObject>
- (void) itemsTableViewController: (ItemsTableViewController *)sender
didSelectProduct: (Product *) aProduct;
@end
@interface ItemsTableViewController : CoreDataTableViewController
@property (nonatomic, strong) UIManagedDocument *itemDatabase;
@property (nonatomic, weak) id <ItemsTableViewControllerDelegate> delegate;
@end
//snippets from the implementation
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
Product *item = [self.fetchedResultsController objectAtIndexPath:indexPath];
[self.delegate itemsTableViewController:self didSelectProduct:item];
NSLog(@"DID SELECT ROW AT index %d with name %@", indexPath.row, item.name);
}
//here's my shopping cart, the ItemsTableViewController delegate
- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if ([segue.identifier isEqualToString:@"Show Products List"]){
ItemsTableViewController *itemsTVC = (ItemsTableViewController *)segue.destinationViewController;
itemsTVC.delegate = self;
}
}
- (void) itemsTableViewController:(ItemsTableViewController *)sender didSelectProduct:(Product *)aProduct{
//adds the product in the shopping cart
[self.shoppingCart addObject:aProduct];
[self.products reloadData];
[self dismissModalViewControllerAnimated:YES];
NSLog(@"from the delegate got product %@", aProduct.name);
}
Upvotes: 0
Views: 390
Reputation: 385500
The destination of your segue is a UINavigationController, not an ItemsTableViewController. Perhaps you put your ItemsTableViewController inside a UINavigationController on your storyboard. Try this:
UINavigationController *navController = segue.destinationViewController;
ItemsTableViewController *itemsTVC = (ItemsTableViewController *)navController.topViewController;
itemsTVC.delegate = self;
Upvotes: 1