【问题标题】:Delegation from a nested navigation stack来自嵌套导航堆栈的委派
【发布时间】:2013-04-01 10:19:40
【问题描述】:

我有标准的视图控制器作为它上面的模态视图控制器的代表。 此模式视图控制器包含在导航控制器中。

在呈现模态并将另一个视图控制器推送到导航堆栈后,我想将一些数据传递回初始委托视图控制器(呈现模态)。

我是否应该先将导航堆栈中的消息传回模态导航控制器的根视图控制器,然后只使用该控制器的委托方法?

我是否应该将委托属性传递给嵌套视图控制器,然后使用实现的单独协议直接调用委托。它可以这样做,但我必须使用

@property (nonatomic, weak) id delegate;

而不是

@property (nonatomic, weak) id <NestedViewDelegate> delegate;

否则,当我从堆栈中的预览视图控制器传递委托时,我会收到不兼容的类型错误:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

{

NestedViewController *nest = [[NestedViewController alloc] init];

// @property id <RootViewControllerDelegate> delegate
[nest setDelegate:[self delegate]];

[[self navigationController] pushViewController:nest animated:YES];

}

这种情况的最佳做法是什么?

谢谢

【问题讨论】:

  • 嗨,Cameron,您成功实施了解决方案吗?你是如何解决这个问题的?我正在寻找解决方案,因为我有同样的问题。
  • 我认为通知是最简单的。

标签: objective-c ios


【解决方案1】:

我会考虑使用通知来解耦。结帐NSNoticationCenter。

您在根目录中注册通知并在您的孩子中发布。

http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/nsnotificationcenter_Class/Reference/Reference.html

示例

在您的 Child 对象中,您可以执行以下操作:

[[NSNotificationCenter defaultCenter] postNotificationName:kMyNotificationName object:self userInfo:@{ @"key" : @"value" }]];

kMyNotificationName 定义在一个共享位置,例如 pch 或 Constants.h。

在 Root 中,您可以在 init 中或在您推孩子时执行类似的操作。

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myNotificationName:) name:kMyNotificationName object:nil];

不要忘记在你的 dealloc 中或者当你弹出子时删除观察者。

[[NSNotificationCenter defaultCenter] removeObserver:self kMyNotificationName object:nil];

现在您可以像这样处理通知:

- (void)myNotificationName:(NSNotification *)note
{
     NSDictionary *userInfo = [note userInfo];

     // Do stuff using the information passed in.
}

【讨论】:

  • 嗨,Cameron,您成功实施了这个解决方案吗?你是如何解决这个问题的?我正在寻找解决方案,因为我有同样的问题。
  • 要了解导航堆栈深处的视图控制器的变化,使用委托并将其链接起来很麻烦。我强烈建议使用通知。
  • @logancautrell 嗨,您可以编辑您的帖子以获得有关如何注册该通知并在孩子中发布的代码的 sn-p 代码吗?我遇到了同样的问题:(
  • 当然,给我几分钟:D
猜你喜欢
  • 2018-03-17
  • 2021-09-22
  • 2018-03-26
  • 1970-01-01
  • 2021-09-02
  • 2019-07-16
  • 2021-12-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多