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!
Access Control and Inheritance Variables declared in implementation file with the help of extensions is not accessible. Methods declared in implementation file with the help of extensions is not accessible. In case the inherited class implements the method in base class, then the method in derived class is executed.
Subclassing : If we want to modify state as well as behaviour of any class or override any methods to alter the behaviour of the parent class then we go for subclassing.
Categories provide the ability to add functionality to an object without subclassing or changing the actual object. A handy tool, they are often used to add methods to existing classes, such as NSString or your own custom objects.
Super is self , but when used in a message expression, it means "look for an implementation starting with the superclass's method table."
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]] ;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With