zoukankan      html  css  js  c++  java
  • 简单介绍ios Delegate的使用

      好久没写blog了~ 今天有同学问delegate的使用,顺便写点东西。

          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,assign) id<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在这个类生命周期结束后还在对僵尸进行操作。

    }

  • 相关阅读:
    配置HDFS HttpFS和WebHDFS
    编译hbase-1.2.3源代码
    Yarn application has already exited with state FINISHED
    一种基于Redis的10行代码实现IP频率控制方法
    PRId64的正确用法
    cmake检测g++编译器是否支持c++11
    定时取指定进程内存脚本
    C++常见gcc编译链接错误解决方法
    Congestion Avoidance in TCP
    Studying TCP's Throughput and Goodput using NS
  • 原文地址:https://www.cnblogs.com/superhappy/p/2679347.html
Copyright © 2011-2022 走看看