zoukankan      html  css  js  c++  java
  • IOS

    在 IOS 的数据回调或者说代理模式大都都是通过回调函数或者Block(代码块)来实现的,Block 没什么好讲的,语法而已,这里简单理解下回调函数的工作原理。

    (这个回调函数的工作原理实际上的也是代理模式的过程)

    一、代理类的实现

    首先,新建一个代理类,并在其中写一个协议:AgencyProtocol

    @protocol AgencyProtocol <NSObject>
    
    - (void)cometrueSuccess:(NSString *)str;
    - (void)cometrueFail:(NSString *)str;
    
    @end

    然后在代理类中操作:

    1. 引入 AgencyProtocol 协议,并且定义一个AgencyProtocol协议的代理(delegate);
    2. 对该代理类使用单例模式(一般代理类使用单例模式比较好,可以防止内存泄露);
    3. 实现一个代理方法;

      .h 文件代码:

    @protocol AgencyProtocol;
    @interface AgencyClass : NSObject
    
    @property (nonatomic, weak) id<AgencyProtocol> delegate;
    
    // 单例模式
    + (id)shareInstance;
    
    /**
     *  模拟代理方法
     *
     *  @param str    表示传进来的参数
     *  @param isBool 模拟判断是否执行成功:即调用协议中的哪个方法
     */
    - (void)agencyFunction:(NSString *)str andBool:(BOOL)isBool;
    
    @end

      .m 文件代码:(这里的代理实现是 回调函数 最重要的地方)

    @implementation AgencyClass
    
    #pragma mark - 单例模式
    static AgencyClass *instnce;
    + (id)shareInstance {
        if (instnce == nil) {
            instnce = [[[self class] alloc] init];
        }
        return instnce;
    }
    
    #pragma mark - 代理实现
    - (void)agencyFunction:(NSString *)str andBool:(BOOL)isBool {
        if (isBool) {
            // 调用 respondsToSelector 方法判断 cometrueSuccess 是否被实现,如果没有实现就去实现它
            if ([self.delegate respondsToSelector:@selector(cometrueSuccess:)]) {
                [self.delegate cometrueSuccess:str];
            }
        } else {
            // 调用 respondsToSelector 方法判断 cometrueFail 是否被实现,如果没有实现就去实现它
            if ([self.delegate respondsToSelector:@selector(cometrueFail:)]) {
                [self.delegate cometrueFail:str];
            }
        }
    }
    
    @end

    二、使用类的实现

    首先,我们在 .h 文件中引入该代理类,并且引入协议

    #import "AgencyClass.h"
    
    @interface ViewController : UIViewController<AgencyProtocol>
    
    @end

    然后我们可以在.m 文件中操作

    1. 创建一个代理类的对象;
    2. 将使用类赋给代理类的 delegate;
    3. 使用代理方法
    //使用代理类
        
        // 创建一个代理类的对象
        AgencyClass *agency = [AgencyClass shareInstance];
        
        // 将使用类赋给代理类的 delegate;
        agency.delegate = self;
        
        // 使用代理方法
        [agency agencyFunction:@"真的在实现?" andBool:YES];

    最后我们可以实现协议的两个方法

    #pragma mark - AgencyProtocol 实现
    - (void)cometrueSuccess:(NSString *)str {
        NSLog(@"%@ 是的,操作成功了!",str);
    }
    
    - (void)cometrueFail:(NSString *)str {
        NSLog(@"%@ 抱歉,操作失败了",str);
    }
  • 相关阅读:
    PHP mysqli_sqlstate() 函数
    修改用户家目录
    mysql 我的学习
    mysql 表空间
    mysql cluster 运行的必备条件
    浅谈mysql集群
    RBAC权限管理
    mysql 恢复备份
    oracle10G/11G官方下载地址集合 直接迅雷下载
    MySQL 全文搜索支持, mysql 5.6.4支持Innodb的全文检索和类memcache的nosql支持
  • 原文地址:https://www.cnblogs.com/ziyeSky/p/4132817.html
Copyright © 2011-2022 走看看