用于多级继承的Objective C [self init]层次结构

kar*_*rim 1 inheritance dynamic objective-c multiple-inheritance ios

我有A类继承了B类.并希望实现类似下面的东西.但是由于动态类型转换,init方法会得到递归调用.有没有办法实现这样的?有什么建议吗?(不改变子类中'init的名字?

@interface A : NSObject
@property NSData * data;
@end
Run Code Online (Sandbox Code Playgroud)
@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
Run Code Online (Sandbox Code Playgroud)
@interface B : A

@end
Run Code Online (Sandbox Code Playgroud)
#import "B.h"

@implementation B

- (id) init {
    self = [super initWithData:nil];
    // some subclass specific init code here ... 
    return 
}
@end
Run Code Online (Sandbox Code Playgroud)

使用B,

- (void) testInit{
    B * b = [[B alloc] init];
}
Run Code Online (Sandbox Code Playgroud)

Cod*_*da1 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;
}
Run Code Online (Sandbox Code Playgroud)

//如果您只想编写一些初始化代码,则以下内容可以正常工作.....

-(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;
}
Run Code Online (Sandbox Code Playgroud)