I'm having trouble understanding the use of [[self alloc] init]
when writing factory methods. I understand that factory methods are convenience methods to create instances of a class, and that they do the alloc
, init
, and autorelease
for you. I can see how this is formed, for example in the declaration of an NSArray
property with the factory method arrayWithArray:
, or array
, etc. called on it to set it up.
I can obviously see how this is different to an outright (explicit) call to alloc
and init
.
My issue with this is that I don't understand factory methods at a deeper level. I came across an explanation online that said instead of calling alloc
and init
explicitly, a class factory method could be used to basically encapsulate something like this:
+(instancetype)createWithString:(NSString *)string
{
return [[self alloc] initWithString:string];
}
But how do instancetype
and [self alloc]
effectively allow for subclasses to make use of the class factory method?