协议的概念: 协议是多个类共享一个方法的列表。其实协议的概念已经说明了它本身的目的。
协议定义:
@protocol Printing
-(void) print;
@end
协议的使用:
#import <Foundation/NSObject.h>
#import "Printing.h"//这里使用是双引号
@interface Fraction:NSObject<Printing,NSCopying>{
//定义变量
}
//定义一些接口方法
@end
举例子:
Complex.h
#import <Foundation/NSObject.h>
#import "Printing.h"
@interface Complex:NSObject<Printing>{
double real;
double imaginary;
}
-(Complex*) initWithReal:(double) r andImaginary:(double) i;
-(void) setReal:(double) r;
@end
Complex.m
#import "Complex.h"
#import <stdio.h>
@implementation Complex
......
-(void) print{
//实现
}
@end
main.m
#import <stdio.h>
#import "Complex.h"
int main(int argc,const char *argv[]){
//创建一个新的实例
Complex *comp = [[Complex alloc] initWithReal : 5 andImaginary:15];
id <Printing> printable;
//print complex
printable = comp;
printf("The complex number is:");
[printable print];
printf("\n");
//判断对象是否遵守了协议规则
//这里应该是false
if([comp conformsToProtocol:@protocol(NSCopying)] == YES){
printf(".....");
}
return 0;
} |
|