1

我有继承类 B 的类 A。并希望实现如下所示。但是由于动态类型转换,init 方法会被递归调用。有没有办法做到这一点?有什么建议吗?(不改变子类中的'init's name?

@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

6

您正在调用[self init]导致递归问题的实现..

以这种方式实现:

- (id) init {
    self = [super init];
    //Basic empty init...
    return self;
}

- (id) initWithData:(NSData *)d 
{
    self = [super init]; //<---- check this line.

    if(self)
    {  
        self.data = d;
    }
    return self;
}

//如果您只想编写一些初始化代码 1 次以下可以工作.....

-(void)oneTimeWrittenInitCode:(id)mySelf
{
    //your init code which you wish to write one time goes here...
}    

- (id) init {
    self = [super init];
    if(self)
    {
       [self oneTimeWrittenInitCode:self];
    }
    return self;
}

- (id) initWithData:(NSData *)d 
{
    self = [super init];

    if(self)
    {  
        [self oneTimeWrittenInitCode:self];
        self.data = d;
    }
    return self;
}
于 2013-10-28T13:08:38.280 回答
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 回答