转自:http://my.oschina.net/wbei/blog/89325
detegate委托在IOS中是一种随处可见的模式,通俗的说,就是我把想做的某件事委托给其他人去做,就好像Java中的接口一样,我只用定义方法的实现,不用过问实现的过程。
Demo下载:http://pan.baidu.com/share/link?shareid=131942&uk=101519637
创建一个委托并声明一个方法![](http://static.oschina.net/uploads/space/2012/1114/222617_2V2B_220404.png)
1 |
#import <Foundation/Foundation.h> |
2 |
@protocol TestDetegate <NSObject> |
3 |
- ( void )setValue:(NSString *)string; |
在委托中,并没有实现setValue这个方法的内容,而在下面的AView.m中实现这个方法
02 |
- ( void )setValue:(NSString *)string |
04 |
aTextLabel.text = string; |
07 |
- (IBAction)clickPush:(id)sender |
09 |
BView *bview = [[BView alloc] initWithNibName:@ "BView" bundle:nil]; |
10 |
bview.text = @ "AView" ; |
12 |
bview.detegate = self; |
13 |
[self.navigationController pushViewController:bview animated:YES]; |
在BView.h中
01 |
#import <UIKit/UIKit.h> |
02 |
#import "TestDetegate.h" |
04 |
@interface BView : UIViewController |
05 |
@property (nonatomic, retain) IBOutlet UILabel *bTextLabel; |
06 |
@property (nonatomic, assign) id <TestDetegate> detegate; |
07 |
@property (nonatomic, retain) NSString *text; |
08 |
- (IBAction)clickBack:(id)sender; |
当点击Push这个Button的时候,设置BView的Label为AView,完成了由父窗口向子窗口传值
![](http://static.oschina.net/uploads/space/2012/1114/223506_4RXz_220404.png)
当点击Back后返回AView时,通过委托改变AView的label值,实现了子窗口到父窗口的传值
![](http://static.oschina.net/uploads/space/2012/1114/223533_jE10_220404.png)
![](http://static.oschina.net/uploads/space/2012/1114/223901_JM7v_220404.png)