且构网

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

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

更新时间:2022-06-05 21:39:00

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

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.

希望这有帮助!