Objective-C2.0文法メモ プロトコル

Objective-Cではあるクラスのインターフェースを定義するのにプロトコルという仕組みを利用します。Javaでいうインターフェース、C++では純粋仮想関数によるクラス定義に相当するものです。書式は以下のようになります。

プロトコルの定義
@protocol MyProtocol
@required // 省略可
-(void) requiredMessage;
@optional
-(void) optionalMessage;
@end

requiredは必ず実装しなければならないメソッド、optionalはその名前通り必要があれば実装できるメソッドです。これらの識別子を省略するとデフォルトではrequiredになるので、通常はrequiredを省略して定義します。

プロトコルのクラスへの適用
@interface MyClass:SubClass <MyProtocol>
@end

@implementation MyClass
- (void) requierdMessage
{

}
@end
実装例

メソッドdrawを規定するプロトコルDrawableを作成して、Circleクラスに適用した例です。

#import <Foundation/Foundation.h>

@protocol Drawable
-(void) draw;
@optional
-(void) fill;
@end

@interface Circle:NSObject <Drawable>
{
    int x;
    int y;
    int raius;
}
@end

@implementation Circle
- (void) draw
{
    NSLog(@"draw");
}
@end

int main (int argc, const char * argv[])
{
    Circle *circle = [[Circle alloc]init];
    [circle draw];
    [circle release];
    return 0;
}

プロトコルの継承

JavaのInterface同様にプロトコルも継承させることができます。クラスに適用した後は基底・派生両方のメソッドを実装する必要があります。

@protocol BaseProtocol
-(void) baseMessage;
@end

@protocol DerivedProtocol<BaseProtocol>
-(void) derivedMessage;
@end

@interface MyClass:NSObject <DerivedProtocol>
@end

@implementation MyClass
- (void) baseMessage
{
}
- (void) derivedMessage
{
}
@end

プロトコルの多重定義

Javaのインターフェースと同様に複数のプロトコルを一つのクラスでまとめて実装することもできます。

@protocol FirstProtocol
-(void) firstMessage;
@end

@protocol SecondProtocol
-(void) secondMessage;
@end

@interface MyClass2:NSObject <FirstProtocol, SecondProtocol>
@end

@implementation MyClass2
- (void) firstMessage
{
}
- (void) secondMessage
{
}
@end