protocol协议时为了补充Objective-C 只能单继承的缺陷而增加的一个新功能。Objective-C重所有的方法都是虚方法,所以在oc重也就没有关键字 virtual一说,有了协议可以补充
Objective-C单继承的缺陷,协议并不是一个真正的类,在协议的里面只声明方法不实现,并且在协议当中不能声明实例变量,如果一个类实现了某一个协议的方法,那么称折各类遵
循(遵守,采用)了这个协议,正式的协议在类中必须被实现,一个类可以实现多个协议,一个协议也可以被多个类实现,
格式 format:
@protocol protocol_name<protocol,....>
required_Method_Declarations //默认是required 在类中必须被实现
@optional
optional_Method_Declarations // 在类中可以选择性的实现,
@required
required_Method_Declarations //在类中必须被实现,
@end
// MyPoint.h #import <Foundation/Foundation.h>
//xieyi 协议 protocol
@protocol showOn
@required
-(void)printOn;
@end
// lei
@interface MyPoint : NSObject<showOn,NSCopying>{
int x;
int y;
}
@property (nonatomic,assign)int x,y;
-(id)initWithX:(int)_x andY:(int)_y;
@end
// leibie fenlei category 分类
@interface MyPoint(MoveSet) -(void)moveToX:(int)_x andY:(int)_y; @end
// MyPoint.m #import "MyPoint.h" @implementation MyPoint
@synthesize x,y;
-(id)initWithX:(int)_x andY:(int)_y{
if(_x==0)
x=1;
if(_y==0)
y=1;
x=_x;
y=_y;
return self;
}
//copyWithZone 方法,避免浅拷贝
-(id)copyWithZone:(NSZone *)zone{
MyPoint* newPoint=[[MyPoint allocWithZone:zone] initWithX:x andY:y];
return newPoint;
}
-(void)printOn{
NSLog(@" x = %d , y = %d ",x,y);
}
@end
@implementation MyPoint(MoveSet)
-(void)moveToX:(int)_x andY:(int)_y{
x=_x;
y=_y;
}
@end
// Circle.h #import <Foundation/Foundation.h>
#import "MyPoint.h" @interface Circle : NSObject<showOn>{
MyPoint* point;
int radius;
}
@property (nonatomic,copy)MyPoint* point;
@property (nonatomic,assign)int radius;
-(id)initWithPoint:(MyPoint* )_p andRadius:(int)_r;
-(id)initWithPoint:(MyPoint *)_p ;
@end
// Circle.m #import "Circle.h" @implementation Circle
@synthesize point;
@synthesize radius;
//重写初始化方法
-(id)initWithPoint:(MyPoint *)_p andRadius:(int)_r{
if(_r==0)
{
radius=1;
}
if(_p==nil)
return nil;
if(self=[super init])
{
if(point!=_p)
{
if(point)
[point release];
point =[[MyPoint alloc]initWithX:_p.x andY:_p.y];
} }
radius=_r;
return self;
}
//重写初始化方法,
-(id)initWithPoint:(MyPoint*)_p{
self=[self initWithPoint:_p andRadius:10];
return self;
}
//实现协议中的方法。
-(void)printOn{
NSLog(@"point(x,y) = (%d,%d),radius = %d",point.x,point.y,radius);
}
@end