使用dismissViewControllerAnimated传回数据

我有一个FirstViewController和一个SecondViewController 。 我在FirstViewController中创建了一个按钮,以便以模态方式对SecondViewController执行segue。

SecondViewController我有一个tableView,显示了8个项目的列表,当我从该列表中选择一个项目时,我将dismissViewControllerAnimated:返回到FirstViewController

我想要做的是将字符串传递回FirstViewController

我使用这篇文章作为我的代码的参考: dismissModalViewController并传回数据

所以这就是我所拥有的:

在FirstViewController.h中

 #import  #import "AppDelegate.h" #import "SecondViewController.h" @interface FirstViewController : UIViewController  @end 

在FirstViewController.m中

 #import "FirstViewController.h" @interface FirstViewController () @end @implementation FirstViewController ... - (void)secondViewControllerDismissed:(NSString *)stringForFirst { NSString *theString = stringForFirst; NSLog(@"String received at FirstVC: %@",theString); } @end 

在SecondViewController.h中

 #import  @protocol SecondDelegate  -(void) secondViewControllerDismissed:(NSString *)stringForFirst; @end @interface SecondViewController : UIViewController  { __weak id myDelegate; } @property (nonatomic, weak) id myDelegate; @property (weak, nonatomic) IBOutlet UITableView *myTableView; @end 

在SecondViewController.m中

 #import "SecondViewController.h" @interface SecondViewController () @end @implementation SecondViewController @synthesize myDelegate; @synthesize myTableView; ... - (int)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } - (int)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return 8; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [atributoTableView dequeueReusableCellWithIdentifier:@"MainCell"]; if(cell == nil){ cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MainCell"]; } cell.textLabel.text = //strings from an array here; return cell; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { if([self.myDelegate respondsToSelector:@selector(secondViewControllerDismissed:)]) { [self.myDelegate secondViewControllerDismissed:@"SOME STRING HERE"]; NSLog(@"string passed"); } [self dismissViewControllerAnimated:YES completion:nil]; NSLog(@"SecondViewController dismissed"); } @end 

当我运行应用程序时,我可以从FirstViewController转到SecondViewController ,当我从tableView中选择一行时,我会回到FirstViewController就好了。 问题是字符串“SOME STRING HERE”没有被传回。

我错过了什么?

顺便说一句,我不确定这是否相关:我正在使用ARC和Storyboard。

您必须在呈现第二个视图控制器时设置委托,即在FirstViewController中:

 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { if ([segue.identifier isEqualToString:@"present_secondviewcontroller]) { SecondViewController *svc = (SecondViewController *)segue.destinationViewController; svc.delegate = self; } } 

根据你的问题和上面提到的解决方案,你应该添加svc.myDelegate = self; 而不是svc.delegate = self;