Subclassing Objective C Class methods

inheritance, ios, objective-c, oop

Solution

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]] ;
}

Problem

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!

Original source