我有一个基类,它有一个自定义的init方法,然后使用通过init方法传入的值,然后在它的子类上调用自定义init方法。问题是当我尝试通过子类Via super
访问在基类中赋值的变量时,值为null,就像基类是一个完全不同的对象。是因为基类还没有从它的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;
}
答案 0 :(得分: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
添加属性,以便不会发生递归初始化。