Reputation: 5194
I have a question regarding Subclassing and Class methods.
I have a base class MyBaseClass
which has a convenience class method
+ (id)giveMeAClassUsing:(NSString *)someParameter;
MyBaseClass
is not a singleton.
Now, I wish to create a subclass of MyBaseClass
, let's call it MyChildClass
. I wish to have the same class method on MyChildClass
as well. Additionally, I also wish to initialize an instance variable on MyChildClass
when I do that.
Would doing something like this:
+ (id)giveMeAClassUsing:(NSString *)someParameter {
MyChildClass *anInstance = [super giveMeAClassUsing:someParameter];
anInstance.instanceVariable = [[UIImageView alloc] initWithFrame:someFrame];
return anInstance;
}
be valid?
Thanks for all your help (in advance) and for resolving my confusion and clarifying some concepts!
Cheers!
Upvotes: 5
Views: 6578
Reputation: 64022
That will work fine.
Possibly better would be to define your convenience constructor in such a way that you don't need to override it:
+ (id)myClassWithString: (NSString *)string {
return [[[self alloc] initWithString:string] autorelease];
}
This will do the right thing no matter which of your superclass or any of its subclasses it is called in.
Then change just the initWithString:
method in your subclass to handle the initialization:
- (id)initWithString: (NSString *)string {
return [self initWithString:string andImageView:[[[UIImageView alloc] initWithFrame:someFrame] autorelease]] ;
}
Upvotes: 8
Reputation: 187302
Absolutely that's valid.
One note though is in the superclass, reference the class itself with self
, rather than the superclass by name.
This is bad:
// MySuperClass // BAD :(
+ (id)giveMeAClassUsing:(NSString *)someParameter {
return [[[MySuperClass alloc] initWithParam:someParameter] autorelease];
}
But this is good!
// MySuperClass // GOOD! :D
+ (id)giveMeAClassUsing:(NSString *)someParameter {
return [[[self alloc] initWithParam:someParameter] autorelease];
}
Otherwise when you subclass, and then call super you aren't actually initializing the right class. Use of self
allows the class being instantiated to vary without overriding the class method.
Upvotes: 5