之前在StackOverFlow上看到一篇讲传值(segue传值和delegate传值)的文章,感觉讲的很清晰,就将delegate部分翻译了一下,有兴趣可以看看。
原文:
http://stackoverflow.com/questions/5210535/passing-data-between-view-controllers
译文:
为了从ViewControllerB往回传值到ViewControllerA,我们需要使用协议(Protocols)和代理(Delegates)。
为了实现这个过程,我们需要设置ViewControllerA为ViewControllerB的代理。这样可以使ViewControllerB能够发送消息到ViewControllerA,同样也能使我们将数据回传。
ViewControllerA作为ViewControllerB的代理必须要遵从我们在ViewControllerB中定义的协议(Protocols),这能够告诉ViewControllerA有哪些方法是必须要实现的。
@classViewControllerB;// Important @protocol ViewControllerBDelegate <NSObject> |
注:(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"; |
在实际工程中我是这样完成的:
- (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 |
6. 最后,在我们将 ViewControllerB 压入堆栈之前,我们需要告诉 ViewControllerB , ViewControllerA 是它的代理 (delegate) :
ViewControllerB *viewControllerB = [[ViewControllerB alloc] initWithNib:@"ViewControllerB" bundle:nil]; |
在实际工程中我是这样做的:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
UIViewController * viewController = segue.destinationViewController;
BAGSelectPeopleVC * selectPeopleVC = (BAGSelectPeopleVC *)viewController;
selectPeopleVC.delegate =self;
}