2

SKNode only offers +node method.

If you do this:

+ (instancetype)node {
    CustomNode *body = [CustomNode node]; // infinite loop
}

If you do this:

+ (instancetype)node {
    CustomNode *body = [super node]; // instance of SKNode, not CustomNode
}

How do you subclass a class that only has a convenience constructor in such way that you can override the constructor? Or is it best practice to create your own +customNode method?

CodeSmile
  • 64,284
  • 20
  • 132
  • 217
openfrog
  • 40,201
  • 65
  • 225
  • 373

3 Answers3

7

No one's saying you can't use [... alloc] init] on an SKNode subclass. After all, SKNode is a subclass of NSObject. +node is just a convenience method.

+ (instancetype)node {
    CustomNode *body = [[self alloc] init];
    return body;
}

There's nothing wrong with this.

dalton_c
  • 6,876
  • 1
  • 33
  • 42
1
+ (instancetype)node {
    CustomNode *body = [CustomNode node]; // infinite loop
}

And infinite loop is the expected result, since you are calling the same method. As for the other one:

+ (instancetype)node {
    CustomNode *body = [super node]; // instance of SKNode, not CustomNode
}

The goal here is for you to make your CustomNode get initialised as expected. It's the same thing when you create a UIViewController for example:

if ( self == [super initWithNibName:nibName bundle:bundle])

You want to do the standard initialisation. What you do after, is what makes your CustomNode a custom node. :)

+ (instancetype)node {
    CustomNode *body = [super node];
    // My own logic goes here

   return body;
}
Rui Peres
  • 25,741
  • 9
  • 87
  • 137
0

The solution is actually to do nothing. The default implementation of +[SKNode node] returns an instance of whatever class or subclass it is called on.

Don't override +[SKNode node] in your subclass. Instantiate instances of your class as in the following example:

// In MyScene.m
// MyNode is a SKNode subclass

- (void)createNewNode
{
    MyNode *node = [MyNode node]; // node is of type MyNode

    [self addChild:node];
}
Russell Ladd
  • 341
  • 3
  • 4