从父类继承属性

时间:2014-01-27 21:10:31

标签: ios objective-c inheritance properties

我认为这是100%直截了当,现在感觉不止有点愚蠢 。我有一个基于NSObject的班级NORPlayer,带有公共财产:

@property (nonatomic, strong) NSArray *pointRollers;

然而,这不是由子类继承的。 数组设置如下,它可以正常工作:

PARENT-CLASS:

@implementation NORPlayer

- (instancetype)init{
    self = [super init];
    if (self) {
        [self setup];
    }
    return self;
}


- (void)setup{
    NSMutableArray *tempRollersArray = [[NSMutableArray alloc] init];
    for (NSUInteger counter = 0; counter < 5; counter++) {
        NORPointRoller *aRoller = [[NORPointRoller alloc] init];
        [tempRollersArray addObject:aRoller];
    }
    _pointRollers = [NSArray arrayWithArray:tempRollersArray];
}

尝试创建从NORPlayerNORVirtualPlayer的子类时,但是出现问题:

SUB-CLASS:

#import "NORPlayer.h"

@interface NORVirtualPlayer : NORPlayer

// none of the below properties nor the method pertains to the problem at hand
@property (nonatomic, assign) NSArray *minimumAcceptedValuePerRound;
@property (nonatomic, assign) NSUInteger scoreGoal;
@property (nonatomic, assign) NSUInteger acceptedValueAdditionWhenScoreGoalReached;

- (void)performMoves;

@end

NORVirtualPlayer的初始化正在使用调用设置方法的init方法镜像其父类:

@implementation NORVirtualPlayer

- (instancetype)init{
    self = [super init];
    if (self) {
        [self setup];
    }
    return self;
}


- (void)setup{
    self.minimumAcceptedValuePerRound = @[ @5, @5, @5, @5, @5 ];
    self.scoreGoal = 25;
    self.acceptedValueAdditionWhenScoreGoalReached = 0;
}

问题是NORVirtualPlayer个实例永远不会获得已发起的pointRollers属性。我已经介绍了所有内容,并且调用了parentClass中的setup方法,因为它是子类...

这感觉它一定是一个相当基本的问题,但我只是无法绕过它。任何帮助将不胜感激。干杯!


解决方案:如下所述。令人尴尬,但仍然很开心。感谢Putz1103首先到达那里。我认为super的设置将通过其init-method调用,但不是那么明显......

1 个答案:

答案 0 :(得分:4)

我没有看到NORPlayer的设置是从NORVirtualPlayer调用的,这是初始化数组的地方。

- (void)setup{
    self.minimumAcceptedValuePerRound = @[ @5, @5, @5, @5, @5 ];
    self.scoreGoal = 25;
    self.acceptedValueAdditionWhenScoreGoalReached = 0;
}

你是否也想打电话给你的超级设置?

- (void)setup{
    [super setup];
    self.minimumAcceptedValuePerRound = @[ @5, @5, @5, @5, @5 ];
    self.scoreGoal = 25;
    self.acceptedValueAdditionWhenScoreGoalReached = 0;
}