使用委托和协议在2个UIViewController之间传递数据

tec*_*man 20 delegates protocols uiviewcontroller ios

我知道这个问题在这里被多次询问和回答.但是我第一次处理这个问题,仍然无法在脑海中完美地实现它.下面是我的委托方法我实现了从传递数据的代码SecondViewControllerFirstViewController.

FirstViewController.h

#import "SecondViewController.h"

@interface FirstViewController : UITableViewController<sampleDelegate> 
@end
Run Code Online (Sandbox Code Playgroud)

FirstViewController.m

@interface FirstViewController ()

// Array in which I want to store the data I get back from SecondViewController.
@property (nonatomic, copy) NSArray *sampleData;
@end

@implementation FirstViewController
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
   SecondViewController *controller = [[SecondViewController alloc] init];          
   [self.navigationController pushViewController:controller animated:YES];
}
@end
Run Code Online (Sandbox Code Playgroud)

SecondViewController.h

@protocol sampleDelegate <NSObject>
- (NSArray*)sendDataBackToFirstController;
@end

@interface SecondViewController : UITableViewController
@property (nonatomic, strong) id <sampleDelegate> sampleDelegateObject;
@end
Run Code Online (Sandbox Code Playgroud)

SecondViewController.m

@interface SecondViewController ()
@property (strong, nonatomic) NSArray *dataInSecondViewController;
@end

@implementation SecondViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.dataInSecondViewController = [NSArray arrayWithObjects:@"Object1", @"Object2", nil];
}

- (NSArray*)sendDataBackToFirstController
{
    return self.dataInSecondViewController;
}
@end
Run Code Online (Sandbox Code Playgroud)

我做得对吗?我只希望它发送数据self.dataInSecondViewControllerFirstViewController并存储在那里的NSArray财产sampleDataFirstViewController.

不知怎的,我不能够访问sendDataBackToFirstControllerFirstViewController.我还缺少哪些其他东西来实现访问sendDataBackToFirstController

gda*_*vis 11

不太对劲.首先,您需要在第一个视图控制器中分配delegate属性,以便第二个视图控制器知道要将消息发送到哪个对象.

FirstViewController.m

controller.delegate = self;
Run Code Online (Sandbox Code Playgroud)

其次,您向后发送和接收您的委托方法.您可以通过FirstViewController sendDataBackToFirstController在第二个控制器上调用的方式进行设置.在委托模式中,SecondViewController是发送消息并可选择使用该方法发送数据的模式.所以,你应该将你的委托声明改为这样的:

@protocol sampleDelegate <NSObject>
- (void)secondControllerFinishedWithItems:(NSArray* )newData;
@end
Run Code Online (Sandbox Code Playgroud)

然后,当您的SecondViewController完成其任务并需要通知其委托时,它应该执行以下操作:

// ... do a bunch of tasks ...
// notify delegate
if ([self.delegate respondsToSelector:@selector(secondControllerFinishedWithItems:)]) {
    [self.delegate secondControllerFinishedWithItems:arrayOfNewData];
}
Run Code Online (Sandbox Code Playgroud)

我在这里添加了一个额外的if语句来检查以确保委托将在实际发送之前响应我们想要发送它的方法.如果我们的协议中有可选方法但没有这个,应用程序就会崩溃.

希望这可以帮助!