无法从第二个视图控制器接收回调

时间:2017-02-13 05:25:45

标签: ios objective-c callback delegates

我有两个视图控制器。我试图将数据传递给以前的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

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

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];

1 个答案:

答案 0 :(得分:2)

您的代码似乎绝对正确,但要解决所有可能性。 你能检查一下你的完成按钮操作是否检查了该类中是否有委托方法?

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");
}