我有两个视图控制器。我试图将数据传递给以前的viewcontroller

我的第二个视图控制器CEPeoplePickerNavigationController中有以下代码

@class CEPeoplePickerNavigationController;
@protocol CEPeoplePickerNavigationControllerDelegate <NSObject>
- (void)previousViewController:(CEPeoplePickerNavigationController *)controller itemToSend:(NSString *)item;
@end


@interface CEPeoplePickerNavigationController : UIViewController <UITableViewDelegate,UITableViewDataSource>{
}
@property (nonatomic, retain) id < CEPeoplePickerNavigationControllerDelegate> peoplePickerDelegate;
@end


当用户单击“完成”按钮时,将执行以下代码

- (void)doneAction:(id)sender
{
    [self.peoplePickerDelegate previousViewController:self itemToSend:@"From Previous VC"];
    [self dismissViewControllerAnimated:YES completion:nil];
}


在我的第一个视图控制器中,我在头文件中具有以下接口,并且当然已经在我的第一个视图控制器中实现了必须接收数据的previousViewController方法。

@interface CallViewViewController : UIViewController<CEPeoplePickerNavigationControllerDelegate>
@end


当我从第一个视图控制器移动到第二个视图控制器时,Im使用以下代码。

CEPeoplePickerNavigationController *nextVc = [[CEPeoplePickerNavigationController alloc] init];
    nextVc.peoplePickerDelegate = self;

    [self presentViewController:nextVc animated:YES completion:nil];


但是,当用户单击第二个视图控制器中的完成按钮时,我在第一个视图控制器中未收到任何回调。为什么这样?

我已经实现了如下界面,

- (void)previousViewController:(CEPeoplePickerNavigationController *)controller itemToSend:(NSString *)item
{
    NSLog(@"from CEPeoplePickerNavigationController %@",item);
}


更新:

以下代码有效

if ([[CallViewViewController new] respondsToSelector:@selector(previousViewController:item:)]) {
    [self.viewCrtrlDelegate previousViewController:self item:@"Here I am"];
    [self dismissViewControllerAnimated:YES completion:nil];
}
else{
   NSLog(@"Your delegate was properly set");
}


但是如果我按照以下方式尝试,则无法正常工作

if ([[self.viewCrtrlDelegate respondsToSelector:@selector(previousViewController:item:)]) {
    [self.viewCrtrlDelegate previousViewController:self item:@"Here I am"];
    [self dismissViewControllerAnimated:YES completion:nil];
}
else{
   NSLog(@"Your delegate was properly set");
}


这就是我实例化视图控制器的方式。

CEPeoplePickerNavigationController *nextVc = [[CEPeoplePickerNavigationController alloc] init];

    nextVc.viewCrtrlDelegate = self;
    [self presentViewController:nextVc animated:YES completion:nil];

最佳答案

您的代码似乎绝对正确,但是可以避免所有可能。
您是否可以检查完成的按钮动作是否可以检查委托方法在该类中是否可用?

if ([self.viewCrtrlDelegate respondsToSelector:@selector(previousViewController:item:)]) {
    [self.viewCrtrlDelegate previousViewController:self item:@"Here I am"];
    [self dismissViewControllerAnimated:YES completion:nil];
}
else{
   NSLog(@"Your delegate was properly set");
}

10-08 15:04