ObjectiveC学习之旅(七)协议protocol

一、什么是协议

  1、协议是多个对象之间协商的一个接口对象

  2、协议提供一系列方法用来在协议的实现者和代理者之间的一种通信方式

  3、协议类似于C++中的纯虚函数,或者java/.net中的接口

二、如何定义协议

  1、协议声明,就放在.h文件中,不像类的定义,声明放在.h文件中,实现放在.m文件中。

  @protocol MyProtocol<NSObject>

    //要定义的变量

    - (void) init;

    -(int) update:(int)time;

  @end

  2、Protocol声明一系列方法,这些放在实现Protocol中实现

  3、协议方法可以实现optional,可选实现,就是说标有@optional的是可选实现的,默认的也是可选实现的。标有@required的是必须实现的。这一点和java/.net就不同了,java/.net中实现了接口的类中的方法必须全部实现。

  4、协议需要继承与基协议NSObject

  5、协议可以多继承

三、如何使用协议

  O-C中判断某个对象是否相应方法

  1、既然接口可以部分实现,OC对象提供了动态判断某个方法是否实现的方法

  2、respondsToSelector

  if([test respondsToSelector:@selector(showInfo)]){

  [test showInfo];

  }

四、代码实例:

定义一个协议:MyProtocol.h

View Code
#import <Foundation/Foundation.h>

@protocol MyProtocol <NSObject>

@optional
- (void) print:(int)value;
// print: 是可选的

@required
- (int) printValue:(int)value1 andValue:(int)value2;
// printValue:andValue: 这个方法是必须要实现的

@end

定义一个MyTest的类
MyTest.h

View Code
#import <Foundation/Foundation.h>
#import "MyProtocol.h"

@interface MyTest : NSObject <MyProtocol>

- (void) showInfo;

@end

MyTest.m

View Code
#import "MyTest.h"

@implementation MyTest

- (void) showInfo
{
    NSLog(@"show info is calling");
}
// 下面这2个方法是来源于 MyProtocol协议
- (int) printValue:(int)value1 andValue:(int)value2
{
    NSLog(@"print value value1 %d value2 %d",
          value1, value2);
    return 0;
}

- (void) print:(int)value
{
    NSLog(@"print value %d", value);
}

@end

main.m

View Code
#import <Foundation/Foundation.h>
#import "MyTest.h"
#import "MyProtocol.h"

int main (int argc, const char * argv[])
{
    @autoreleasepool {
        // insert code here...
        NSLog(@"Hello, World!");
        MyTest *myTest = [[MyTest alloc] init];
        [myTest showInfo];
        SEL sel = @selector(print:);
        // 这个pirnt: 转化成 SEL类型的 方法
        if ( [myTest respondsToSelector:sel] ) {
            // 判断 myTest是否 响应 sel方法 (print:)
            [myTest print:20];
        }
        [myTest printValue:10 andValue:21];
        [myTest release];
        
        // 用协议方式
        id <MyProtocol> myProtocol = [[MyTest alloc] init];
        if ( [myProtocol respondsToSelector:@selector(print:)] ) {
            [myProtocol print:102];
        }
        [myProtocol printValue:103 andValue:105];
        
        [myProtocol release];
    }
    return 0;
}

  

原文地址:https://www.cnblogs.com/caishuhua226/p/2830448.html