私はクラス B を継承するクラス A を持っています。そして、以下のようなことを達成したいと考えています。しかし、init メソッドは動的な型キャストのために再帰呼び出しを取得します。そのようなことを達成する方法はありますか?なにか提案を?(サブクラスの 'init' の名前を変更せずに?
@interface A : NSObject
@property NSData * data;
@end
@implementation A
- (id) init {
self = [super init];
/* want to do some default initialization here
for this class and all of its subclasses. */
// ... ...
return self;
}
/* This [self init] get recursed.
But how can I force this class and all of its subclass to call [self init] above,
not to call the subclass's init method. */
- (id) initWithData:(NSData *)d {
self = [self init];
self.data = d;
return self;
}
@end
@interface B : A
@end
#import "B.h"
@implementation B
- (id) init {
self = [super initWithData:nil];
// some subclass specific init code here ...
return
}
@end
Bを使って、
- (void) testInit{
B * b = [[B alloc] init];
}