Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2611029
  • 博文数量: 877
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 5921
  • 用 户 组: 普通用户
  • 注册时间: 2013-12-05 12:25
个人简介

技术的乐趣在于分享,欢迎多多交流,多多沟通。

文章分类

全部博文(877)

文章存档

2021年(2)

2016年(20)

2015年(471)

2014年(358)

2013年(26)

分类: iOS平台

2015-07-13 18:12:20


http://www.cnblogs.com/superhappy/archive/2012/09/10/2679347.html

ios 的 delegate经常出现在 model 与 controller之间的通信。delegate中文叫做委托,就是委托别人帮你完成的意思。比如 我写了个interface,服务器返给我我要的数据,同时告诉我success,那么我在controller怎么接收到这个interface的信息呢。 我的实现是这样子的:在interface中写一个delegate,(这个delegate 可以直接继承自 Objective - C protocol,也可以直接写在其他的类里面),让返回成功和失败时执行 delegate的方法,在controller中实现这些方法。
由于网络接口都是公司的网址,不方便。所以简单的写个示意程序:

 

 @protocol BaseInterfaceDelegate <NSObject>

 @required//必须实现的代理方法

-(void)parseResult:(ASIFormDataRequest *)request;

-(void)requestIsFailed:(NSError *)error;

@optional//不必须实现的代理方法

@end

@interface BaseInterface : NSObject <DefaultLoginInterfaceDelegate,ASIHTTPRequestDelegate> {

    ASIFormDataRequest *_request;

 }

 @property (nonatomic,assignid<BaseInterfaceDelegate> baseDelegate; //一般delegate都是assign的防止循环circular count产生。

-(void)connect;

 @end

 

@implementation BaseInterface

 

@synthesize baseDelegate = _baseDelegate;

-(void)connect {

    写网络请求

}

 

#pragma mark - ASIHttpRequestDelegate//网络情求的代理ASIHttpRequestDelegate

-(void)requestFinished:(ASIFormDataRequest *)request {

        [_baseDelegate parseResult:request];//用实例变量delegate执行代理方法 表示一旦返回成功就执行这个方法,而这个方法究竟执行什么操作,就需要建立这个类对像的controller去实现。

}

 

-(void)requestFailed:(ASIFormDataRequest *)request {

        [_baseDelegate requestIsFailed:request.error];//用实例变量delegate执行代理方法 表示一旦返回失败就执行这个方法,而这个方法究竟执行什么操作,就需要建立这个类对像的controller去实现。

}

 

@interface MyController:UIViewController <DefaultLoginInterfaceDelegate> {

   BaseInterface *interface;

 }

 

@implementation MyController;

这个类中的其他方法省略,只写delegate方法

//对delegate方法的实现

-(void)parseResult:(ASIFormDataRequest *)request

{

   对返回的 request做相应的操作,并对界面做相应的操作。

}

 

-(void)requestIsFailed:(NSError *)error

{

  对返回的 error做相应的操作,并对界面做相应的操作。

}

-(void)dealloc

{

self.delegate = nil;//防止delegate在这个类生命周期结束后还在对僵尸进行操作。

}

阅读(685) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~