Search code examples
iossprite-kitsklabelnode

SKLabelNode when added to class throws attempted to add nil node error


I'm following along this Spritekit tutorial http://code.tutsplus.com/tutorials/ios-sdk-build-a-facts-game-interface-creation--mobile-20764

And they suggest to add a timer's text in the viewDidLoad Method. The code that is given in the tutorial looks like this:

_timerLevel = [SKLabelNode labelNodeWithFontNamed:@"Chalkduster"];
_timerLevel.text = @"30";
_timerLevel.fontSize = 70;
_timerLevel.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame)+350);
[self addChild:_timerLevel];

Once I run the line [self addChild:_timerLevel] the error 'attempted to add nile node error to parent' is thrown.

And _timerLevel is declared in the interface as

@property (nonatomic,weak) SKLabelNode* timerLevel;

The scene is initalised like so:

-(id) initWithSize:(CGSize)size inLevel:(NSInteger)level withPlayerLives:(int)lives {
    if (self = [super initWithSize:size]) {
        self.backgroundColor = [SKColor colorWithRed:0.35 green:0.25 blue:0.5 alpha:1.0];
        defaults = [NSUserDefaults standardUserDefaults];

        playerLives = lives;
        playerLevel = level;

        maximumTime = 30;

    }


    return self;
}

Is the error telling me that the _timerLevel hasn't been initialised and is therefore nil? How do I initialise it correctly? Many thanks


Solution

  • Either remove the weak keyword:

    @property (nonatomic) SKLabelNode* timerLevel;
    

    Or assign the label to a local variable first:

    SKLabelNode* timerLevel = [SKLabelNode labelNodeWithFontNamed:@"Chalkduster"];
    _timerLevel = timerLevel;
    

    The problem with the use of weak here is that after initializing the label, there is no strong reference holding on to it unless you either assign it to a local variable or remove the weak keyword. Otherwise the label is initialized, returned, and immediately deallocates and set to nil even before the next line executes.