tableView: didSelectRowAtIndexPath: inconsistency

220 Views Asked by At

I'm fairly new to Objective-C and iOS app development so I apologize if the answer to my question is simple. I'm trying to send a pointer of a GTGift object from one view controller to another. When I enter the following code, the object is send and stored in an instance variable of the second view controller:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    GTGift *selectedGift = [[[GTGiftStore sharedStore] allGifts] objectAtIndex:[indexPath row]];
    GTDetailViewController *dvc = [[self storyboard] instantiateViewControllerWithIdentifier:@"detailVC"];
    [dvc setDetailGift:selectedGift];
    [[self navigationController] pushViewController:dvc animated:YES];
}

However, when I enter this code in the first view controller:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    gift = [[[GTGiftStore sharedStore] allGifts] objectAtIndex:[indexPath row]];
    GTDetailViewController *dvc = [[self storyboard] instantiateViewControllerWithIdentifier:@"detailVC"];
    [[self navigationController] pushViewController:dvc animated:YES];
}

And this code in the second view controller:

- (void)viewWillAppear:(BOOL)animated {
    GTGiftsViewController *gvc = [[self storyboard] instantiateViewControllerWithIdentifier:@"giftsVC"];
    detailGift = [gvc gift];
    NSLog(@"%@", detailGift);
}

detailGift returns null.

I can't for the life of me understand why, and it would be much more practical for my application if I could use an approach similar to the code segment that does not work. If anyone can shine some light on this topic for me or point me in a different direction to complete the same task I would really appreciate it!

1

There are 1 best solutions below

3
On BEST ANSWER

Your problem is that the word "instantiate" means what it says. :-)

In viewWillAppear you're creating a brand new GTGiftsViewController object which knows nothing about the gift that's been selected in the first GTGiftsViewController object.

(The "storyboard way" of doing this kind of thing is to create a prepareForSegue:sender: method in your first view controller and do the work there.)