0

我有一个具有自定义 init 方法的基类,然后使用通过 init 方法传入的值在其子类上调用自定义 init 方法。问题是当我尝试通过子类 Via 访问在基类中分配了值的变量时,super这些值为空,就像基类是一个完全不同的对象。是因为基类还没有从它的 init 方法返回吗?还是我在这里继承错误?要遵循的代码。

界面

@interface WTFGameBoard : NSObject
{
    @protected
    UIView *_answerView;
    UIView *_keyboardView;
    NSMutableArray* _answerSeperatedByCharacter;

    WTFAnswerBoard *_answerBoard;
    WTFGameKeyboard *_gameKeyboard;

    OpenGameViewController *_weakGameViewRef;
    GameInfo *_gameinfo;
}

-(id) initWithGameVC:(OpenGameViewController*)gameVC;

@property (nonatomic,unsafe_unretained)OpenGameViewController *weakGameViewRef;
@property (nonatomic,strong)GameInfo *gameInfo;

@end

执行

@implementation WTFGameBoard
@synthesize weakGameViewRef = _weakGameViewRef;
@synthesize gameInfo = _gameinfo;

-(id) initWithGameVC:(OpenGameViewController*)gameVC
{
    if (self = [super init])
    {
        //[weakGameViewRef ]
        _answerView = [gameVC answerView];
        _keyboardView = [gameVC keyboardView];

        self.weakGameViewRef = gameVC;
        self.gameInfo = [[CurrentGamesInfo sharedCurrentGamesInfo]_selectedGame];

        _answerBoard = [[WTFAnswerBoard alloc] initWithAnswer:[gameVC answer] blankSpaceImageView:[gameVC answerBox]];
        _gameKeyboard = [[WTFGameKeyboard alloc] initWithButtons:[gameVC letterSelectButtons]];

    }

    return self;
}

@end

界面

@interface WTFAnswerBoard : WTFGameBoard
{
    NSMutableArray *WTFAnswerSpaces;
    NSMutableArray *_answerBlankBlocks;
    NSMutableArray *_answerGiven;
    NSMutableArray *_answerBlankOriginalPosition;
    NSString *_answer;
}

-(id)initWithAnswer:(NSString*)answer blankSpaceImageView:(UIImageView*)answerBox;

执行

-(id)initWithAnswer:(NSString*)answer blankSpaceImageView:(UIImageView*)answerBox
{
    if ( self = [super init] )
    {
        _weakGameViewRef = [super weakGameViewRef];//WHY U NO NOT BE NULL?
        _gameinfo = [super gameInfo];//WHY U NO NOT BE NULL?

        _answerBlankBlocks = [_weakGameViewRef answerBlankBlocks];
        _answerGiven = [_weakGameViewRef answerGiven];
        _answerBlankOriginalPosition = [_weakGameViewRef answerBlankOriginalPosition];

        [self SetupBlankAnswerSpacesForAnswer:answer withTemplate:answerBox];
    }

    return self;
}
4

1 回答 1

0

问题是您没有在派生类中调用自定义构造函数:

if ( self = [super init] )

您正在调用默认值,它没有被覆盖,并且不会初始化您尝试访问的 ivars。

您应该调用自定义构造函数:

if ( self = [super initWithGameVC:gameVC] )

当然,这意味着您需要传递参数,或者通过初始化您想要初始化的内容来覆盖默认构造函数,而无需任何参数。

我不明白的另一件事是为什么要在自定义类中设置派生类的 ivars:

_weakGameViewRef = [super weakGameViewRef];

这基本上什么都不做,因为 ivar 是相同的,如果您设置基类之一,那么您可以直接访问它。

编辑

因为你在这里有一个奇怪的依赖问题,一个快速的解决方案是有类似的东西

WTFAnswerBoard initWithWTFGameBoard:(WTFGameBoard*)board {
  self.board = board;
}

这样您就可以访问实例化WTFAnswerBoard并保持继承但将使用切换为组合的板(通过添加一个属性来WTFAnswerBoard使您的递归初始化不会发生。

于 2013-01-25T04:27:31.333 回答