T. Benjamin Larsen
T. Benjamin Larsen

Reputation: 6383

inheriting property from parent-class

I thought this was 100% straight-forward and am feeling more than a bit dumbfounded right now. I have an NSObject based class NORPlayer with a public property:

@property (nonatomic, strong) NSArray *pointRollers;

This is however not inherited by the sub-class. The array is set up like this, and it works just fine:

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];
}

When trying to create a subclass from NORPlayer to NORVirtualPlayer however something goes awry:

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

The initialization of NORVirtualPlayer is mirroring its parent-class with the init method calling a setup method:

@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;
}

The problem is that the NORVirtualPlayer instances never get an initiated pointRollers property. I've stepped through everything and the setup method in the parentClass is called as are the subclass...

This feels like it must be a fairly basic problem but I'm just not able to wrap my head around it. Any help would be greatly appreciated. Cheers!


Solution: Like stated below. Embarrassing, but happy nevertheless. Kudos to Putz1103 for actually getting there first. I figured the super's setup would be called by its init-method but not so obviously...

Upvotes: 1

Views: 214

Answers (1)

ansible
ansible

Reputation: 3579

I don't see your NORPlayer's setup getting called from NORVirtualPlayer, which is where the array is initialized.

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

Did you want to call your super's setup too?

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

Upvotes: 4

Related Questions