12
12

More than 5 years have passed since last update.

Objective-CでAbstractパターン

Posted at

Objective-CでAbstractパターンを書く。Abstractクラスのヘッダにメソッドを定義して、継承したクラスで実装を行う。Abstractクラスのメソッドが呼び出された場合には例外を送出するようにする。

Abstractクラスのヘッダと実装

parentClass
@interface parentClass : NSObject

- (void)someMethod;

@end


@implement parentClass

- (void)someMethod
{
    // 継承したクラスで実装する
    [NSException raise:NSInternalInconsistencyException
                format:@"You must override %@ in a subclass", NSStringFromSelector(_cmd)];
}

@end

継承したクラスの実装

childClass.m
@interface childClass : parentClass
@end


@implement childClass

- (void)someMethod
{
    // 実装を書く
}

@end

呼び出し(書く必要ないと思うけど)

- (void)hogehoge
{
    childClass *cls = [[childClass alloc] init];
    [cls someMethod];
}
12
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
12