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 ???
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;
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
.
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
?