且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-06-20 21:39:52

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

Not quite right. First you need to assign the delegate property in the first view controller so the second view controller knows which object to send messages to.

FirstViewController.m

FirstViewController.m

controller.delegate = self;

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

Second, you have the sending and receiving of your delegate method backwards. You have it setup in a way where the FirstViewController is expected to call sendDataBackToFirstController on the second controller. In a delegate pattern, the SecondViewController is the one that sends the message and optionally sends data with that method. So, you should change your delegate declaration to something like this:

@protocol sampleDelegate <NSObject>
- (void)secondControllerFinishedWithItems:(NSArray* )newData;
@end

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

Then, when your SecondViewController finishes its tasks and needs to notify its delegate, it should do something like this:

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

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

I added an extra if statement here to check to make sure the delegate will respond to the method we want to send it before actually sending it. If we had optional methods in our protocol and did not have this, the app would crash.

希望这会有所帮助!