在兩個視圖控制器之間傳遞數據似乎已經使用委託來解決。我的情況有點不同,既然我是新人,我不知道我能否與代表解決。iOS:將數據從ChildViewController傳遞給GrandParentViewController?
我有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
?
- 一般來說,我如何將數據從一個子控制器傳遞迴任何祖先控制器?
UPDATE
現在,我已經添加了2名代表來解決這個問題
一)從Child
到Parent
b 1名代表。)1名代表從Parent
到GrandParent
這工作,但我不認爲這是一個好的設計,數據需要在兩個或更多的視圖控制器之間傳遞,因爲最終會創建新的代理來傳遞值。
那麼,我使用委託在vcs之間傳遞這種數據。但我也使用CoreData或NSUser在vcs之間共享一些其他數據。 – leonard 2014-11-24 03:44:37