0

I am trying to understand what is difference between initializing a subclass using [super init] vs [SuperClassType classMethod]. Below are the code examples:

-(instancetype)initWithAPPImageName:(NSString *)appImageName {

    SKTextureAtlas *atlas = [SKTextureAtlas atlasNamed:@"character"];
    self = (AppNode *)[super initWithTexture:[atlas textureNamed: appImageName]];

    if(self)
    {
        self.name = @"appNode";

        if([self isKindOfClass:[AppNode class]])
        {
            self.position = [self GetPosition];
        }
    }

    return  self;
}

Here it works as expected. self is kind of AppNode, but below, it always returns SKSpriteNode even though casting. What is different?

-(instancetype)initWithAPPImageName:(NSString *)appImageName {

    SKTextureAtlas *atlas = [SKTextureAtlas atlasNamed:@"character"];
    self = (AppNode *)[SKSpriteNode spriteNodeWithTexture:[atlas textureNamed:appImageName]];

    if(self)
    {
        self.name = @"appNode";

        if([self isKindOfClass:[AppNode class]])
        {
            self.position = [self GetPosition];
        }
    }

    return  self;
}
godel9
  • 7,340
  • 1
  • 33
  • 53
Sureyya Uslu
  • 325
  • 4
  • 10

1 Answers1

3

Short answer: Your first block of code is correct, and your second block of code is incorrect.

init methods are INSTANCE methods. An init method gets sent to a freshly created object that already exists, and it's job is to set up the object for use.

In an init method for a custom subclass you call the superclass's init method so that the superclass has a chance to do whatever setup is needed for the superclass. Then you do the init code specific to your custom subclass.

In your second block of code, you discard the object that was allocated and use an SKSpriteNode class method to create a new object of type SKSpriteNode. Casting an object to a different class type simply suppresses a compiler warning - it does not change the class of the object.

Duncan C
  • 128,072
  • 22
  • 173
  • 272