OC中协议类似于java中的接口,在多个类具有类似的方法时可以将这些方法定义到protocol中,然后各个类分别实现protocol中的各个方法。

例:有两个类Square和Circle, 定义一个protocol来获得对象的面积, Square和Circle只需实现protocol中的-(int)area方法即可。

定义协议

@protocol AreaProtocol<NSObject>

- (int) area;

@end

//square类

@interface Square:NSObject<AreaProtocol>

{

 int side;

}

@end

@implementation Square

- (int)area {

  return side * side;

}

@end

 


//circle类

@interface Circle:NSObject<AreaProtocol>

{

 int r;

}

@end

@implementation Circle

- (int)area {

  return π * r * r;

}

@end

posted on 2016-02-21 00:30  ximenchuixie  阅读(108)  评论(0编辑  收藏  举报