轉(zhuǎn)自:http://blog.csdn.net/vesper305/article/details/40598313
之前在StackOverFlow上看到一篇講傳值(segue傳值和delegate傳值)的文章疏橄,感覺講的很清晰范舀,就將delegate部分翻譯了一下,有興趣可以看看瓣距。
原文:
http://stackoverflow.com/questions/5210535/passing-data-between-view-controllers
譯文:
為了從ViewControllerB往回傳值到ViewControllerA唬党,我們需要使用協(xié)議(Protocols)和代理(Delegates)。
為了實(shí)現(xiàn)這個(gè)過程,我們需要設(shè)置ViewControllerA為ViewControllerB的代理著拭。這樣可以使ViewControllerB能夠發(fā)送消息到ViewControllerA,同樣也能使我們將數(shù)據(jù)回傳牍帚。
ViewControllerA作為ViewControllerB的代理必須要遵從我們?cè)赩iewControllerB中定義的協(xié)議(Protocols)儡遮,這能夠告訴ViewControllerA有哪些方法是必須要實(shí)現(xiàn)的。
1.在ViewControllerB.h中履羞,在#import和@interface之間(就是代碼位置)峦萎,我們像下面這樣定義我們的協(xié)議及協(xié)議方法:@classViewControllerB;// Important
@protocol ViewControllerBDelegate <NSObject>- (void)addItemViewController:(ViewControllerB *)controller didFinishEnteringItem:(NSString *)item;@end
注:(NSString *)item是我們現(xiàn)在要回傳的數(shù)據(jù)類型,也可以是其他類型忆首,如字典爱榔、數(shù)組等
2.仍然是在ViewControllerB.h中,設(shè)置一個(gè)delegate屬性糙及,同時(shí)在ViewController.m中synthesize
@property (nonatomic, weak) id <ViewControllerBDelegate>delegate;
在工程中我是這么做的:
@propertyid<SelectPeopleVCDelegate>delegate;
3.在ViewControllerB中详幽,我們?cè)趯⒁獜膶?dǎo)航控制器中彈出該視圖的時(shí)候向代理發(fā)送消息(消息中含有我們要傳遞的值)
NSString *itemToPassBack = @"Pass this value back to ViewControllerA";[self.delegate addItemViewController:self didFinishEnteringItem:itemToPassBack];
在實(shí)際工程中我是這樣完成的:
- (void)viewDidDisappear:(BOOL)animated
{
[self.delegateaddItemViewController:selfdidFinishSelectPeople:dataSourceArray];
}
注:dataSourceArray是我的數(shù)據(jù)源,在一個(gè)公開變量浸锨,在前面的程序中完成賦值唇聘。
4.以上就是所有要在ViewControllerB中進(jìn)行的操作,接下來就是ViewControllerA的操作柱搜。首先我們要在ViewControllerA.h中導(dǎo)入ViewControllerB迟郎,并遵從它的協(xié)議:
#import "ViewControllerB.h"
@interface ViewControllerA :UIViewController <ViewControllerBDelegate>
5.在ViewControllerA.m中實(shí)現(xiàn)協(xié)議方法:
- (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];
在實(shí)際工程中我是這樣做的:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
UIViewController * viewController = segue.destinationViewController;
BAGSelectPeopleVC * selectPeopleVC = (BAGSelectPeopleVC *)viewController;
selectPeopleVC.delegate =self;
}