small medium large xlarge

26 Mar 2014, 16:30
Tim Hoolihan (2 posts)

Maybe this is addressed later, but I’m fairly early on and have a question. In the step I’m at, I have 3 different methods which refer tot he ship in SpaceRun. They all query for the node by name.

Is there any reason not to create a property and save a reference to the node when creating it?

@property (nonatomic) SKSpriteNode *ship;

#... then in initWithSize:
        self.ship = [SKSpriteNode spriteNodeWithImageNamed:name];

I tried it in a branch and it works, but I wondered if this is bad practice to have a reference to the node. Thanks, Tim

30 Mar 2014, 14:21
Jonathan Penn (44 posts)

You certainly can store them in properties! This is Objective-C in all it’s property laden glory.

However, our goal with the book was to help people think in terms of storing the game state within the scene graph itself. It’s a powerful way of representing where the game is currently at.

Since SKNode’s are serializable (using NSKeyedArchiver) everything about them is captured when you serialize it, including the node names and all that. When a node is deserialized then everything picks up exactly where it left off. If you’ve been searching through the scene graph for nodes by name, your code is immediately ready to rumble.

But if you’ve been keeping track of nodes in properties then it is your responsibility to populate those properties when the node is reconstituted.

That’s just one example. We don’t teach saving game state because it was beyond the pedagogical goals for this introductory book (and would require much more complicated demos). But that’s a common use case for why you’d want to keep as much data represented in a scene graph as possible.

We felt it important to just teach tracking nodes by name as the normal course of using Sprite Kit. If you want to use properties, go for it!

31 Mar 2014, 13:28
Tim Hoolihan (2 posts)

Thanks for the follow up! That’s exactly the info I was looking for