为了从ViewControllerB往回传值到ViewControllerA,我们需要使用协议(Protocols)和代理(Delegates)。
为了实现这个过程,我们需要设置ViewControllerA为ViewControllerB的代理。这样可以使ViewControllerB能够发送消息到ViewControllerA,同样也能使我们将数据回传。
ViewControllerA作为ViewControllerB的代理必须要遵从我们在ViewControllerB中定义的协议(Protocols),这能够告诉ViewControllerA有哪些方法是必须要实现的。
1.在ViewControllerB.h中,在#import和@interface 之间(就是代码位置),我们像下面这样定义我们的协议及协议方法:
@class ViewControllerB;// Important
@protocol ViewControllerBDelegate <NSObject>
- (void)addItemViewController:(ViewControllerB *)controller didFinishEnteringItem:(NSString *)item;
@end
注:(NSString *)item是我们现在要回传的数据类型,也可以是其他类型,如字典、数组等
2.仍然是在ViewControllerB.h中,设置一个delegate属性,同时在ViewController.m中synthesize
@property (nonatomic, weak) id <ViewControllerBDelegate>delegate;
在工程中我是这么做的:@propertyid<SelectPeopleVCDelegate>delegate;
3.在ViewControllerB中,我们在将要从导航控制器中弹出该视图的时候向代理发送消息(消息中含有我们要传递的值)
NSString *itemToPassBack = @"Pass this value back to ViewControllerA";
[self.delegate addItemViewController:self didFinishEnteringItem:itemToPassBack];
在实际工程中我是这样完成的:
- (void)viewDidDisappear:(BOOL)animated
{
[self.delegateaddItemViewController:selfdidFinishSelectPeople:dataSourceArray];
}
注:dataSourceArray是我的数据源,在一个公开变量,在前面的程序中完成赋值。
4.以上就是所有要在ViewControllerB中进行的操作,接下来就是ViewControllerA的操作。首先我们要在ViewControllerA.h中导入ViewControllerB,并遵从它的协议:
#import "ViewControllerB.h"
@interface ViewControllerA :UIViewController <ViewControllerBDelegate>
5.在ViewControllerA.m中实现协议方法:
- (void)addItemViewController:(ViewControllerB *)controller didFinishEnteringItem:(NSString *)item
{
NSLog(@"This was returned from ViewControllerB %@",item);
}
6.最后,在我们将ViewControllerB压入堆栈之前,我们需要告诉ViewControllerB,ViewControllerA是它的代理(delegate):
ViewControllerB *viewControllerB = [[ViewControllerB alloc] initWithNib:@"ViewControllerB" bundle:nil];
viewControllerB.delegate = self
[[self navigationController] pushViewController:viewControllerB animated:YES];
在实际工程中我是这样做的:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
UIViewController * viewController = segue.destinationViewController;
BAGSelectPeopleVC * selectPeopleVC = (BAGSelectPeopleVC *)viewController;
selectPeopleVC.delegate =self;
}