Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subclassing Objective C Class methods

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!

like image 867
codeBearer Avatar asked Apr 25 '12 18:04

codeBearer


People also ask

How do you inherit a class in Objective C?

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.

When should I use subclass?

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.

What is the use of category in Objective C?

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.

What is super in Objective C?

Super is self , but when used in a message expression, it means "look for an implementation starting with the superclass's method table."


1 Answers

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]] ;
}
like image 163
jscs Avatar answered Sep 29 '22 22:09

jscs