1

私はクラス 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];
}
4

4 に答える 4

1

「指定された初期化子」パターンを調べます。クラス階層にイニシャライザ メソッドと便利なコンストラクタ (別名ファクトリ メソッド) を配置する方法について説明します。

于 2013-10-28T23:17:35.030 に答える
1

上記の指定された初期化子パターンの例を次に示します。

#import ”Person.h”

@implementation Person
-(id) initWithAge:(int)theAge AndHeight:(int)theHeight AndName:(NSString *)theName {
  if (self = [super init]){
    _age = theAge;
    _height = thefleight;
    _name = theName;
  }
  return self;
} 

-(id) initwithAge:(int)theAge AndHeight:(int)theHeight {   
  return [self initWithAge:theAge AndHeight:theHeight AndName:nil];
}

-(id) initwithAge:(int)theAge {
  return [self initWithAge:theAge AndHeight:0];
}  

- (id)init {
  return [self initwithAge:0];
}
@end
于 2014-01-03T14:13:38.750 に答える
0

そのはず:

- (instancetype) initWithData:(NSData *)d
{
    if(self = [super init])
    {
       _data = d;
    }
    return self;
}
于 2013-10-28T13:18:59.203 に答える