简体   繁体   English

tableView:didSelectRowAtIndexPath:不一致

[英]tableView: didSelectRowAtIndexPath: inconsistency

I'm fairly new to Objective-C and iOS app development so I apologize if the answer to my question is simple. 我对Objective-C和iOS应用程序开发还很陌生,因此对于我的问题的答案很简单,我深表歉意。 I'm trying to send a pointer of a GTGift object from one view controller to another. 我正在尝试将GTGift对象的指针从一个视图控制器发送到另一个视图控制器。 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. detailGift返回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! 如果有人可以为我提供有关此主题的启发,或者将我指向另一个方向来完成相同的任务,我将不胜感激!

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. viewWillAppear您正在创建一个全新的GTGiftsViewController对象,该对象对第一个GTGiftsViewController对象中选择的礼物GTGiftsViewController

(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.) (做这种事情的“ storyboard方式”是在第一个视图控制器中创建prepareForSegue:sender:方法并在那里进行工作。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM