首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将数据从ChildViewController传递到ParentViewController

将数据从ChildViewController传递到ParentViewController
EN

Stack Overflow用户
提问于 2014-06-10 02:59:06
回答 1查看 444关注 0票数 1

我有两个视图,ParentViewControllerChildViewController;我想在ParentViewController中嵌套ChildViewController。我在故事板中设计了ParentViewControllerChildViewControllerParentViewController.m包含父对象的逻辑,ChildViewController.m包含子对象的逻辑。在ParentViewController.m中,我像这样添加子对象:

代码语言:javascript
复制
 ChildViewController *childVC = [self.storyboard instantiateViewControllerWithIdentifier:@"ChildSBI"];
 [self addChildViewController:childVC];

我的问题是:如何将信息(如NSString)从子进程接收回父进程?我应该通过delegation完成此操作吗

EN

回答 1

Stack Overflow用户

发布于 2014-06-10 03:11:15

一种常见的模式是将child作为parent的属性,并将parent作为child的委托。你需要做的第一件事就是制定你自己的协议。

代码语言:javascript
复制
// MyProtocol.h
- (void)heyParentSomethingHappened:(Something)something;

接下来,将child设置为parent的属性,以便它们可以通过委托进行通信。

代码语言:javascript
复制
// ParentVC.m
@interface ParentVC()
@property (nonatomic) ChildVC *child
@end

既然parent已经将child作为一个属性,那么他们就需要用某种方式来交流。这就是委派的用武之地。使父级符合MyProtocol

代码语言:javascript
复制
// ParentVC.h
@interface ParentVC : UIViewController <MyProtocol>

既然parent符合您的特殊协议,就让child将其作为委托。

代码语言:javascript
复制
//ChildVC.h 
@interface ChildVC : UIViewController
@property (nonatomic) id <MyProtocol> delegate.
@end

现在child有了delegate属性,将其设置为parent就可以了。

代码语言:javascript
复制
// ParentVC.m
- (id)init {
    // do your init
    self.child.delegate = self // both (child.delegate, self) conform to <MyProtocol>, so no type mismatch.
}

现在,当你的child需要提醒你的parent一些事情时,他们有一个正式的方式通过协议+委托进行交谈。

代码语言:javascript
复制
// ChildVC.m
- (void)someFunc {
    [self.delegate heyParentSomethingHappend:[Something new]];
}

请记住,在使用协议文件时,一定要将其包括在内。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24127057

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档