Object-C中的协议Protocol

版权所有,禁止匿名转载;禁止商业使用。




在写C# 的时候都会有接口interface这个概念,接口就是一堆方法的声明没有实现,而在OC里面,Interface是一个

类的头文件的声明,并不是真正意义上的接口的意思,在OC中,接口是由一个叫做协议的protocol来实现的。这个里面

可以声明一些方法,和C#不同的是,它可以声明一些必须实现的方法和选择实现的方法。这个和C#是完全不同的。

下面我们就用一个例子来说明这个吧。

首先是MyProtocol.h也就是接口的声明文件


//  
//  MyProtocol.h  
//  Protocol  
//  
//  Created by bird on 12-10-22.  
//  Copyright (c) 2012年 bird. All rights reserved.  
//  
  
#import <Foundation/Foundation.h>  
  
@protocol MyProtocol <NSObject>  
  
@optional  
//这个方法是可选的  
- (void) print:(int) value;  
  
@required  
//这个方法是必须实现的  
- (int) printValue:(int) value1 andValue:(int) value2;  
  
@end


然后是Mytest.h也就是类的声明文件,这个类讲实现这个接口


//  
//  MyTest.h  
//  Protocol  
//  
//  Created by bird on 12-10-22.  
//  Copyright (c) 2012年 bird. All rights reserved.  
//  
  
#import <Foundation/Foundation.h>  
#import "MyProtocol.h"  
  
@interface MyTest : NSObject <MyProtocol>  
  
- (void) showInfo;  
  
@end  
下面就是实现文件了
[cpp] view plaincopyprint?
//  
//  MyTest.m  
//  Protocol  
//  
//  Created by bird on 12-10-22.  
//  Copyright (c) 2012年 bird. All rights reserved.  
//  
  
#import "MyTest.h"  
  
@implementation MyTest  
  
- (void) showInfo  
{  
    NSLog(@"show info is calling");  
}  
  
- (int) printValue:(int)value1 andValue:(int)value2  
{  
    NSLog(@"print info that value1 is %d and value2 is %d",value1,value2);  
    return 0;  
}  
  
//下面的这个方法可以实现也可以不实现  
- (void) print:(int)value  
{  
    NSLog(@"print is value is %d",value);  
}  
  
@end


这样我们就可以看出了,这个类实现了接口也就是协议的声明的方法,然后还定义了自己的类方法。


下面我们来看一下主函数来使用这个接口,我将分别使用两种方式来使用这个类,一个是基本的方法就是使用类的创

建来调用,另一个就是使用接口来调用


//  
//  main.m  
//  Protocol  
//  
//  Created by bird on 12-10-18.  
//  Copyright (c) 2012年 bird. All rights reserved.  
//  
  
#import <Foundation/Foundation.h>  
#import "MyTest.h"  
#import "MyProtocol.h"  
  
int main(int argc, const char * argv[])  
{  
  
    @autoreleasepool {  
          
        //这里是普通的类的调用方法  
        MyTest * myTest = [[MyTest alloc] init];  
        [myTest showInfo];  
          
        SEL sel = @selector(print:);//这个print转换成的方法  
        //确定这个print方法是否实现  
        if([myTest respondsToSelector:sel]){  
                [myTest print:20];  
        }  
          
          
        [myTest printValue:25 andValue:15];  
        [myTest release];  
          
        //下面的方法使用协议的方式来调用  
        id<MyProtocol> myProtocol = [[MyTest alloc] init];  
        if([myProtocol respondsToSelector:@selector(print:)]){  
            [myProtocol print:210];  
        }  
          
        [myProtocol release];  
    }  
    return 0;  
}


[myProtocol respondsToSelector:@selector(print:)]

这句话的用处就是测试是否这个类实现了这个方法


0 0