【发布时间】:2014-11-24 03:18:07
【问题描述】:
在两个视图控制器之间传递数据似乎已经使用委托解决了。我的情况略有不同,由于我是新手,我不知道我是否可以与代表一起解决这个问题。
我有 3 个视图控制器。 GrandParent、Parent 和 Child。GrandParent 实例化 Parent,显示 CategoryGroups 的列表。
单击CategoryGroup 实例化Child 视图控制器,显示Categories 列表。
我希望当用户点击任何Category 时,GrandParent 会知道被点击的Category。
我现在有什么?
在Child.h 视图控制器上
@protocol CategorySelectDelegate<NSObject>
- (void) categorySelected:(CategoryModel *) categoryModel;
@end
在Child.m 视图控制器上
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(@"selected category:%@", _categories[(NSUInteger) indexPath.row]);
[self.delegate categorySelected:_categories[(NSUInteger) indexPath.row]];
[self dismissViewControllerAnimated:YES completion:nil];
}
开启GrandParent.h
@interface GrandParent : UIViewController<CategorySelectDelegate>
开启GrandParent.m
- (void)viewDidLoad {
[super viewDidLoad];
ChildViewController *categoryViewController = [[ChildViewController alloc] init];
childViewController.delegate = self;
}
- (void)categorySelected:(CategoryModel *)categoryModel {
_categoryLabel.text = categoryModel.name;
NSLog(@"categoryLabel:%@", _categoryLabel.text);
}
但我知道这是不正确的,因为GrandParent 不是直接实例化Child 的那个,它总是生下Child 的父母
问题
- 如何将categoryModel 从Child 传递到GrandParent?
- 一般来说,如何将数据从一个子控制器传回任何祖先控制器?
更新
目前,我已添加 2 个代表来解决此问题
a.) 1 个代表,从 Child 到 Parent
b.) 1 个代表,从 Parent 到 GrandParent
这可行,但我认为这不是一个好的设计,因为数据需要在 2 个或更多视图控制器之间传递,因为最终会创建新的委托来传递值。
【问题讨论】:
-
嗯,我用delegate在vcs之间传递这种数据。但我也使用 CoreData 或 NSUser 在 vcs 之间共享一些其他数据。
标签: ios objective-c iphone ios7