简体   繁体   English

子类化Objective C类方法

[英]Subclassing Objective C Class methods

I have a question regarding Subclassing and Class methods. 我有一个关于Subclassing和Class方法的问题。

I have a base class MyBaseClass which has a convenience class method 我有一个基类MyBaseClass ,它有一个方便类方法

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

MyBaseClass is not a singleton. MyBaseClass不是单身人士。

Now, I wish to create a subclass of MyBaseClass , let's call it MyChildClass . 现在,我希望创建一个MyBaseClass的子类,让我们称之为MyChildClass I wish to have the same class method on MyChildClass as well. 我希望在MyChildClass上也有相同的类方法。 Additionally, I also wish to initialize an instance variable on MyChildClass when I do that. 另外,我还希望在我这样做时在MyChildClass上初始化一个实例变量。

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! 干杯!

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: 然后只更改子类中initWithString:方法来处理初始化:

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

Absolutely that's valid. 绝对是有效的。

One note though is in the superclass, reference the class itself with self , rather than the superclass by name. 一个注意事项是在超类中,使用self引用类本身,而不是按名称引用超类。

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. 否则当你进行子类化,然后调用super时,你实际上并没有初始化正确的类。 Use of self allows the class being instantiated to vary without overriding the class method. 使用self允许实例化的类在不覆盖类方法的情况下变化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM