简述代理与委托的区别

类A.h:

 1 @protocol ADelegate <NSObject>
 2 
 3 -(void)babyAdded:(Baby*)newBaby;
 4 -(void)babyChanged:(Baby*)changedBaby;
 5 
 6 @end
 7 @interface A : UIViewController<UITextFieldDelegate>
 8 
 9 @property(nonatomic,strong) id<ADelegate> delegate;
10 
11 @end

首先在A中定义了一个代理ADelegate,代理中有两个方法,并且定义了待了delegate为id类型的Adelegate

B.h

1 @interface B : UIViewController<ADelegate>
2 
3 @property(nonatomic,strong) IBOutlet UITableView *babyListView;
4 @property(nonatomic,strong) NSMutableArray *babyArray;
5 
6 -(void)appendBaby;
7 
8 @end

我们发现A中的代理ADelegate中的函数在B中实现了,可以把B理解为A的委托,

B.m

 1 @interface BabyListViewController ()
 2 
 3 @end
 4 #define babyInfoLabelTag 100
 5 #define defaultBabyIconTag 200
 6 @implementation BabyListViewController
 7 
 8 @synthesize babyListView,babyArray;
 9 
10 //单击一个cell
11 #pragma mark - UITableViewDelegate impl
12 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
13 {
14     UITableViewCell *cell = (UITableViewCell *)[tableView cellForRowAtIndexPath:indexPath]; 
15     Baby *baby=[babyArray objectAtIndex:indexPath.row];
16     BabyFormViewController *editBabyViewController=  [[BabyFormViewController alloc] initWithNibName:@"BabyFormViewController" bundle:nil];
17     editBabyViewController.delegate=self;
18     editBabyViewController.baby=baby;
19     [self.navigationController pushViewController:editBabyViewController animated:YES];
20 }
21 
22 #pragma mark - BabyFromViewDelegate
23 -(void)babyAdded:(Baby *)newBaby
24 {
25     self.babyArray=[[BabyManager sharedInstance] babyList];
26 //    [[BabyManager sharedInstance] insertBabyInfo:newBaby];
27     [babyListView reloadData];
28 }
29 -(void)babyChanged:(Baby *)changedBaby
30 {
31     NSLog(@"baby chanaged!");
32     self.babyArray=[[BabyManager sharedInstance] babyList];
33     [babyListView reloadData];
34 }
35 
36 @end

22行开始就是实现了,注意17行!把自己设为A的delegate,在这个demo中就是说A.m中如果调用了babyAdded或者babyChanged方法就会自动刷新babyArray方法,1-3行所代表为私有方法

posted @ 2012-07-11 17:19  暖流  阅读(351)  评论(0编辑  收藏  举报