subclassing convenience construtctor
-
28-04-2021 - |
Question
If I have a super class with a convenience constructor as follows (using ARC):
+(id)classA {
ClassA *foo = [[ClassA alloc] init];
return foo;
}
If I then subclass ClassA, with a class named ClassB, and I want to override the convenience constructor, is the following correct:
+(id)classB {
ClassB *foo = [ClassA classA];
return foo;
}
(Assume that I cannot call alloc and init on ClassB).
Thanks!
Solution
No, that is not correct, since that allocates, inits and returns a ClassA, not a ClassB. The only way to do this is not to use ClassA explicitly:
+ (id) classA
{
return [[self alloc] init];
}
Of course, you could also use old-fashioned new
for this:
ClassB *myB = [ClassB new];
FWIW, assuming I would want to do more than just allocate and init, and my class is named Gadget, then I would do something like:
+ (id) gadgetWithNumber: (int) num
{
return [[self alloc] initWithNumber: num];
// or without ARC:
// return [[[self alloc] initWithNumber: num] autorelease];
}
Of course that assumes that there is an initWithNumber:
method in my class.
OTHER TIPS
A class method is passed self
just like an instance method, only in the case of a class method the value of self
is an instance of Class
. So change your classA
method to:
+ (id) classA
{
return [[self alloc] init];
}
(Which is just the definition of new
you inherit from NSObject
. The convention is newX
returns a retained reference, while classnameX
returns an autoreleased reference. Using ARC the difference is really moot, but I'd go with newX
myself.)
Now if ClassB
is a sub-class of ClassA
then [ClassB classA]
will invoke classA
with self
being ClassB
and you will alloc
and init
a ClassB
instance.