iphone - 将数据从 tableviewcontroller 传递到父 viewcontroller

标签 iphone ios objective-c uiviewcontroller delegates

所以目前我有一个 tableviewcontroller,如果发生某种情况,它会以模态方式显示在 loginviewcontroller 上方,然后一旦用户按下单元格,标题就应该传递给父 View Controller 。

所以图片 (A) 是父级 - 主视图,(B) 是登录,(C) 是 tableviewcontroller...

C 位于 B 之上,B 位于 A 之上,不是通过导航堆栈,而是通过模态堆栈。所以 C 除了这个之外没有任何对 A 的引用:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self Login];
    [self.presentingViewController.presentingViewController dismissViewControllerAnimated:YES completion:nil];
}

当用户按下单元格时, View 会直接转到 (A),因此从 (C) 到 (A) 会跳过 (B)。这就是我想要的......但问题是我如何将数据传递给(A)而不必再次实例化(A)?我的意思是再次实例化,它已经在应用程序启动开始时实例化,如果用户尚未登录,则 (B) 显示在 (A) 之上。因此 (A) 始终加载,但我如何传递数据到吗?

如果需要提供更多信息,请通知我,我会尽快编辑。

编辑 我又看了几个与这个相关的问题,我会使用 NSNotification 吗?还是委托(delegate)团?我尝试同时使用两者,但都没有真正起作用...我引用了我之前回答的有关委托(delegate)的问题来实现委托(delegate)解决方案,但我必须在 (A) 中实例化 (C)。但是我已经在 (B) 中实例化了 (C)。这是我要使用但没有使用的 delgation 解决方案:Delegation .这是我尝试使用的 NSNotification 解决方案的链接:

将其放入 viewDidLoad 中的父 Controller

- (void) viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];

    [self makeCallbacks];
    // get register to fetch notification
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(yourNotificationHandler:)
                                                 name:@"MODELVIEW DISMISS" object:nil];
}

//Now create yourNotificationHandler: like this in parent class
-(void)yourNotificationHandler:(NSNotification *)notice{
    str = [notice object];

}

将以下内容添加到您的子类中

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    NSLog(@"%@", cell.textLabel.text);
    // cell.textLabel.text logs this -> EDF ENRS
    [[NSNotificationCenter defaultCenter] postNotificationName:@"MODELVIEW DISMISS" object:cell.textLabel.text];
    [self.presentingViewController.presentingViewController dismissViewControllerAnimated:YES completion:nil];
}

当我记录 'str' (null) 时打印

现在的问题是,当我稍后在 viewWillAppear 中在通知之外记录 str 时,它一直返回 null...。当我在通知方法中记录 str 时,它只会返回 null... 我将尝试解决这个问题稍后发布,但我想主要问题是使用 NSNotificationCenter 解决了。

最佳答案

NSNotificationCenter 不工作背后的问题在于它在 viewDidAppear 中被声明。 确保它在每次显示屏幕时出现并写入进行更改的地方,例如 viewWillAppear

然后,在 viewWillAppear 方法中对父 View 进行必要的更改。

此外,请务必在发布这些通知时在调用的方法中删除通知。

关于iphone - 将数据从 tableviewcontroller 传递到父 viewcontroller,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17845899/

相关文章:

ios - 按特定字符拆分字符串,iOS

iphone - 一个View中可以添加多少个UILabel

objective-c - 音乐未与AVAudioPlayer循环播放

iphone - MPMoviePlayerController thumbnailImageAtTime :timeOption: simple case doesn't work

iphone - NSMutableDictionary 的 JSONRepresentation

objective-c - 如何在 iOS 中使用 twitvid 在 Twitter 上上传视频?

ios - Facebook POP 动画只工作一次

ios - 夏令时与 NSTimeZone 最佳实践

iphone - 我们可以从应用商店获得唯一的交易ID吗

iphone - 将图像添加到iPhone中工具栏的栏按钮项