我知道这个问题在这里被多次询问和回答.但是我第一次处理这个问题,仍然无法在脑海中完美地实现它.下面是我的委托方法我实现了从传递数据的代码SecondViewController
来FirstViewController
.
FirstViewController.h
#import "SecondViewController.h" @interface FirstViewController : UITableViewController@end
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
SecondViewController.h
@protocol sampleDelegate- (NSArray*)sendDataBackToFirstController; @end @interface SecondViewController : UITableViewController @property (nonatomic, strong) id sampleDelegateObject; @end
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
我做得对吗?我只希望它发送数据self.dataInSecondViewController
到FirstViewController
并存储在那里的NSArray
财产sampleData
的FirstViewController
.
不知怎的,我不能够访问sendDataBackToFirstController
在FirstViewController
.我还缺少哪些其他东西来实现访问sendDataBackToFirstController
?
不太对劲.首先,您需要在第一个视图控制器中分配delegate属性,以便第二个视图控制器知道要将消息发送到哪个对象.
FirstViewController.m
controller.delegate = self;
其次,您向后发送和接收您的委托方法.您可以通过FirstViewController sendDataBackToFirstController
在第二个控制器上调用的方式进行设置.在委托模式中,SecondViewController是发送消息并可选择使用该方法发送数据的模式.所以,你应该将你的委托声明改为这样的:
@protocol sampleDelegate <NSObject> - (void)secondControllerFinishedWithItems:(NSArray* )newData; @end
然后,当您的SecondViewController完成其任务并需要通知其委托时,它应该执行以下操作:
// ... do a bunch of tasks ... // notify delegate if ([self.delegate respondsToSelector:@selector(secondControllerFinishedWithItems:)]) { [self.delegate secondControllerFinishedWithItems:arrayOfNewData]; }
我在这里添加了一个额外的if语句来检查以确保委托将在实际发送之前响应我们想要发送它的方法.如果我们的协议中有可选方法但没有这个,应用程序就会崩溃.
希望这可以帮助!