objective-cinheritancefactoryfactory-methodinstancetype

Using superclass instance method in Objective-C


I'm confused in using instancetype in Objective-C.

Code:

@interface MyClass : NSObject

-(instancetype)initWithOwner:(NSString*)anOwner;

@property (nonatomic, strong) NSString* owner;
@end


@interface MyChildClass : MyClass

-(instancetype)init;

@property (nonatomic, strong) NSString* myString;
@end

Then, I'm able to run this

MyChildClass* myChildObject = [[MyChildClass alloc] initWithOwner:@"owner"];

Why does this return MyChildClass and not MyClass ???

Why doesn't compiler show any warning or error message, that I'm using the initializer method of a superclass, and not MyChildClass initializer method ???

Where can I use this ???


Solution

    1. Question (Question marks 1 to 3)

    This is because of instancetype. It says: The return instance is of the same type (or a subclass) as the receiver has.

    [[MyChildClass alloc] initWithOwner:@"owner"];
    

    Means:

    [[MyChildClass alloc] -> MyChildClass
                                          initWithOwner:@"owner"] -> MyChildClass;
    
    1. Question (Question marks 4 to 6)

    a. There are no factory methods in Objective-C. There are methods in Objective-C.

    b. The compiler shows no warning, because everything is fine. You assign a reference to MyChildClass to a reference variable of the type MyChildClass.

    1. Question (Question marks 7 to 9)

    You can use this in your example. MyChildClass can use the base' class implementation, if it does not want to change it. (Very often.)

    BTW: Do you know that the returned instance is of the type MyChildClass?