【深入浅出ios开发】使用代理进行传值

来源:互联网 发布:汪精卫为何叛变知乎 编辑:程序博客网 时间:2024/05/29 17:39

一般在ios开发中通过segue过度进行传值,有些时候可能不行,例如两个UIviewcontroller之间相互传值。这时候我们一般通过代理来进行传值。

由于自己是C++出身,对设计模式也有所了解,这里就简单的用个实例来讲解代理模式如何通过代理进行传值。

某公司接到一个项目,于是项目经理开始写计划,然后进行软件的基本架构。这时候他发现自己一个人无法在预定的时间里完成这个软件。于是他就开始招人,招了一个程序员来写一些方法。

①项目经理让程序员做某些事情,肯定要他遵守某些准则,也就是所谓的协议。

项目经理于是定好协议,在协议中把方法封装好。

[objc] view plaincopy
  1. @protocol MRViewControllerThreeDelegate <NSObject>  
  2. -(void)addPerson: (MRViewControllerThree*)addVc withPersonName:(NSString*)strName withPersonTel:(NSString*)strTel;  
  3. @end  
1.这里@protocol.....@end代表签署一份协议.

2.MRViewControllerThree表示协议的签署人这里就是项目经理,也就是代理者。MRViewControllerThreeDelegate表示项目经理负责代理。

3.<NSObject>表示签署的协议还必须遵守的其他协议。这就像公司给我们签合同一样,首先要遵循劳动法等约束。

4.addPerson方法,也就是我们协议的内容,也就是协议代理者(MRViewControllerThree)要求被代理者

(MRTableViewControllerTwo)干的事情。


②程序员也就是被代理者(MRTableViewControllerTwo)要遵循协议才能做相关的事情。

首先他要得到项目经理的代理:

[objc] view plaincopy
  1. #import "MRViewControllerThree.h"  
  2. @interface MRTableViewControllerTwo ()<MRViewControllerThreeDelegate>  

<MRViewControllerThreeDelegate>就是程序员要引用干的项目经理的代理。

然后,他要告诉项目经理我愿意按照你的代理办事:

[objc] view plaincopy
  1. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender  
  2. {  
  3.     MRViewControllerThree *controllerThree = segue.destinationViewController;  
  4.     controllerThree.delegate = self;  
  5. }  

最后,实现代理中的方法:

[objc] view plaincopy
  1. -(void)addPerson:(MRViewControllerThree *)addVc withPersonName:(NSString *)strName withPersonTel:(NSString *)strTel  
  2. {  
  3.     NSLog(@"----%@-------%@-----%@------",strName,strTel,self);  
  4. }  

这里就是简单的输出代理者要求我们输出的字符串,还有自己的的身份(self)。


③项目经理拿回代理进行确认,然后让调用程序员做事。

[objc] view plaincopy
  1. @interface MRViewControllerThree : UIViewController  
  2. @property(strong,nonatomicid<MRViewControllerThreeDelegate> delegate;  
  3. @end  

[objc] view plaincopy
  1. - (IBAction)backToTwo:(id)sender {  
  2.     //1.返回上一个控制器  
  3.     [self.navigationController popViewControllerAnimated:YES];  
  4.     //2.通知代理,传递数据给上一个控制器  
  5.     if ([self.delegate respondsToSelector:@selector(addPerson:withPersonName:withPersonTel:)]) {  
  6.         NSString *strName = self.textFieldName.text;  
  7.         NSString *strTel = self.textFieldTel.text;  
  8.         [self.delegate addPerson:self withPersonName:strName withPersonTel:strTel];  
  9.     }  
  10. }  
0 0
原创粉丝点击