Objective C Subclass Class Methods

I have a question about subclass and class methods.

I have a base class MyBaseClassthat has a convenience class method

+ (id)giveMeAClassUsing:(NSString *)someParameter;

MyBaseClass not solitary.

Now I want to create a subclass MyBaseClass, call him MyChildClass. I want to have the same class method on MyChildClass. In addition, I also want to initialize the instance variable to MyChildClasswhen I do this.

Would do something like this:

+ (id)giveMeAClassUsing:(NSString *)someParameter {

      MyChildClass *anInstance = [super giveMeAClassUsing:someParameter];
      anInstance.instanceVariable = [[UIImageView alloc] initWithFrame:someFrame];

      return anInstance;
}

permissible?

Thank you for your help (in advance) and for resolving my confusion and clarifying some concepts!

Hooray!

+3
source share
2 answers

This will work fine.

It might be better to define a convenience constructor in such a way that you do not need to redefine it:

 + (id)myClassWithString: (NSString *)string {
     return [[[self alloc] initWithString:string] autorelease];
 }

, , .

initWithString: :

- (id)initWithString: (NSString *)string {
    return [self initWithString:string andImageView:[[[UIImageView alloc] initWithFrame:someFrame] autorelease]] ;
}
+6

.

, , self, .

:

// MySuperClass // BAD :(
+ (id)giveMeAClassUsing:(NSString *)someParameter {
  return [[[MySuperClass alloc] initWithParam:someParameter] autorelease];
}

!

// MySuperClass // GOOD! :D
+ (id)giveMeAClassUsing:(NSString *)someParameter {
  return [[[self alloc] initWithParam:someParameter] autorelease];
}

, , super, . self .

+5

All Articles