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

 

总结:

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

posted @ 2015-01-15 20:36  月之星狼  阅读(318)  评论(0编辑  收藏  举报