Objective-Cプロトコル

2252 ワード

まず、本文は筆者のために「Objective-C基礎教程」のノートを学び、筆者自身の理解とまとめを加えた.

1.プロトコルの作成


プロトコルは、メソッドとプロパティを含む名前付きリストです.@protocolキーワードは、プロトコルを宣言します.
@protocol KeyListener

- (void) onKeyDown;
- (void) onKeyUp;

@end

2.親プロトコルを継承できるプロトコル

@protocol MouseListener 

- (void) onKeyMove;

@end

3.プロトコルのキーワード

@required、強制的に実現しなければならない方法を示す@optional、選択的な実現方法があることを示す

4.実装プロトコル

NSCopyingプロトコルは、オブジェクトをコピーするプロトコルです.ShapeプロトコルNSCopyingを実装し、方法copyWithZoneを実装する.RectangleShapeを継承し、同様に方法copyWithZoneを実装する.
@interface Shape : NSObject 

@property int width;
@property int height;

@end

@implementation Shape 

@synthesize width;
@synthesize height;

- (id) init {
    if (self = [super init]) {
        width = 20;
        height = 20;
        NSLog(@"Shape init");
    }
    return self;
}

- (id) copyWithZone: (NSZone*) zone {
    Shape* shapeCopy = [[[self class] allocWithZone: zone] init];
    shapeCopy.width = width;
    shapeCopy.height = height;

    return shapeCopy;
}

- (NSString*) description {
    return [NSString stringWithFormat: @"(%d, %d)",
            [self width], [self height]];
}

@end

@interface Rectangle : Shape

@property int radius;

@end

@implementation Rectangle

@synthesize radius;

- (id) copyWithZone: (NSZone*) zone {
    Rectangle* rectangleCopy = [super copyWithZone: zone];
    rectangleCopy.radius = [self radius];

    return rectangleCopy;
}

- (NSString*) description {
    return [NSString stringWithFormat: @"(%d, %d) radius = %d",
            [self width], [self height], [self radius]];
}

@end

int main(int argc, const char* argv[]) {
    @autoreleasepool {
        Shape* shape = [[Shape alloc] init];
        shape.width = 30;
        shape.height = 25;
        NSLog(@"%@", [shape copy]);

        Rectangle* rect = [[Rectangle alloc] init];
        rect.width = 100;
        rect.height = 60;
        rect.radius = 5;
        NSLog(@"%@", [rect copy]);
    }
    return 0;	
}