Xcode使用委托在控制器之间传递数据

嗨即时通讯开发一个应用程序,有一个父视图,然后使用容器来embedded其他视图如下所示。

在这里输入图像说明

现在我只使用左侧和中间的容器,这两个视图。 主视图或项目屏幕视图是我的父控制器,我希望它传递数据,并从两个子控制器,我知道这是最好的select是使用代表。 然而,我看过的每个示例都使用委托,创build并初始化一个新的视图控制器,例如让左边的容器使用leftviewcontrollerembedded一个视图。 每个例子都有这一行代码。

LeftViewController *sampleProtocol = [[LeftViewController alloc]init]; LeftViewController.delegate = self; 

我想我不需要创build一个新的LeftViewController,因为它embedded它已经在我的子控制器的列表。 所以我的问题是我如何从控制器的子控制器列表中获取控制器,并将父级设置为委托。 我知道我是一个数组,我可以使用objectAtIndex,但我怎么知道数组中的项目顺序不会改变我可以不叫它,而是一个标签或标识符? 如果问题不是很清楚的话,谢谢你的帮助,那是我第一次设立代表。

我知道这是最好的select是使用代表。

在这种情况下,我不会那么肯定。 我认为最好的select是build立一个健壮的模型,并使用KVO和通知来表示视图控制器之间的更新。


直接回答你的问题是不是太糟糕。

 for (UIViewController *viewController in self.childViewControllers) { if ([viewController isKindOfClass:[LeftViewController class]]) { LeftViewController *leftViewController = (id)viewController; leftViewController.delegate = self; break; } } 

我认为在这方面稍作改进就是使用segue。 确保每个容器都有一个命名的segue。 在这个例子中,左视图控制器有一个segue,标识符为“Load Child LeftViewController”。

 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { if ([segue.identifier isEqualToString:@"Load Child LeftViewController"]) { LeftViewController *leftViewController = segue.destinationViewController; leftViewController.delefate = self; } } 
 Its always better to use NSNotificationCenter for such complex mechanism. 

*** put following code in LeftController.m ***

 // *** Register a Notification to recieve a Data when something happens in Center controller *** [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receivedNotification:) name:@"hasSomeData" object:nil]; // *** create a method to receive Notification data *** - (void)receivedNotification:(NSNotification *) notification { if ([[notification name] isEqualToString:@"hasSomeData"]) { // do your stuff here with data NSLog(@"data %@",[notification object]); } } 

*** when something happen in center controller post a notification to inform Left Controller ***

 [[NSNotificationCenter defaultCenter] postNotificationName:@"hasSomeData" object:self]; 
  //Secondvc.h @protocol Sendmessage<NSObject> @required -(void)Object:(NSArray *)tosend; @end @interface Secondvc:UIViewcontroller{ id <Sendmessage> delegate; } @property(strong,nonatomic) id <Sendmessage> delegate; @end //Secondvc.m @implementation Secondvc @synthesize delegate; -(void)viewDidLoad{ //Do Something here! } //Pass Some Value When a button event occured in Second vc -(IBAction)Send_Data{ [self dismissViewControllerAnimated:Yes completion:nil]; [self.delegate Object:[NSArray Arraywithobjects:@"Hello",nil]]; } @end //FirstVc.h #import "Secondvc.h" @interface FirstVc<Sendmessage> @end //FirstVc.m @implementation FirstVc -(void)viewDidLoad{ Secondvc* Object=[[Secondvc alloc]init]; Object.delegate=self; } #pragma mark Secondvc Deklegate method implementation -(void)Object:(NSArray *)tosend{ NSLog(@"Recieved data Form Second VC Is:\n%@",tosend); } @end 

HTH!享受编码。