• Protocol入门


    参考:http://haoxiang.org/2011/08/ios-delegate-and-protocol/

    介绍:

         Protocol在iOS中就是协议,简单的理解就是一组函数的集合,这个集合中有分为必需实现的和可选实现的。一般来说,protocol会与delegate模式一同使用。说白了,一个protocol就是一组实现规范。

    定义:

    @protocol testProtocol   // 协议名称
    @required                   // 必需实现的方法
    -(void)getTheResult;
    @optional                   // 可选实现的方法
    -(void)running;
    @end    

    使用:

    @interface GameProtocol : NSObject
    @property id<testProtocol> delegate;  // 代理设置
    -(void)runTheGame;
    @end
    
    @implementation GameProtocol
    -(instancetype)init{
    
        self = [super init];
    
        [self addObserver:self forKeyPath:@"delegate" options:NSKeyValueObservingOptionNew| NSKeyValueObservingOptionOld context:@""];
    
        return self;
    
    }
    
     
    
    -(void)dealloc{
    
        if (self) {
    
            [self removeObserver:self forKeyPath:@"delegate"];  //要移除KVO,否则会出错
    
        }
    
    }
    
     
    
    -(void)runTheGame{
    
        [self.delegate getTheResult];
    
    }
    
     
    
    -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    
        if ([keyPath isEqualToString:@"delegate"]) {
    
            [self runTheGame];
    
        }
    
    }
    
    @end

    结合委托模式:

    @interface ProtocolViewController ()<testProtocol>
    
    @end
    
    @implementation ProtocolViewController
    
    #param mark - testProtocol协议
    -(void)getTheResult{ NSLog(@"%@",@"get the result"); } - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. GameProtocol *game = [[GameProtocol alloc]init]; game.delegate = self; [game runTheGame]; }

    输出结果:

    2015-01-15 20:44:58.195 testDemo[10476:2067475] get the result
    2015-01-15 20:44:58.196 testDemo[10476:2067475] get the result

    总结:

         协议就是一组规范,是对一组方法的封装,其他对象调用的时候,只需设置这个代理,然后在该对象中直接调用,这样的话这个对象就能很好的封装,具体的协议实现在调用这个对象的时候再具体实现,这样就能够做到逻辑的封装,与业务逻辑无关。

  • 相关阅读:
    React中路由的基本使用
    React中props
    一款超级炫酷的编辑代码的插件 Power Mode
    React中使用styled-components的基础使用
    对ES6的一次小梳理
    动态规划法(七)鸡蛋掉落问题(二)
    动态规划法(六)鸡蛋掉落问题(一)(egg dropping problem)
    三对角线性方程组(tridiagonal systems of equations)的求解
    Sherman-Morrison公式及其应用
    动态规划法(四)0-1背包问题(0-1 Knapsack Problem)
  • 原文地址:https://www.cnblogs.com/starwolf/p/4227227.html
Copyright © 2020-2023  润新知