2011-02-18 103 views
2

假设我们有一个类Base。Objective-c类创建方法

@inerface Base : NSObject 
{ 
} 
+(id) instance; 
@end 

@implementation Base 
+(id) instance 
{ 
    return [[[self alloc] init] autorelease]; 
} 
-(id) init 
{ 
... 
} 
@end 

而且我们派生了派生类。

@interface Derived : Base 
{ 
} 
@end 

其中重新实现了init方法。

现在我们要使用类方法+(id) instance创建派生类的实例。

id foo = [Derived instance]; 

现在foo实际上是一个基类。

如何在这种情况下实现foo作为派生类?

我应该重新实现派生类的所有类方法吗? (实际上不会完全相同)。

有没有更优雅的方式?

回答

2

当您使用[Derived instance]创建实例时,该实例的类将为Derived。尝试一下。诀窍是在instance方法短信self

+(id) instance 
{ 
    return [[[self alloc] init] autorelease]; 
} 

当您发送instance消息BaseselfBase。当你发送相同的消息到Derived,selfDerived,因此整个事情的工作是理想的。

+0

该死,我写过return [[[Base alloc] init] autorelease];在我的代码中的实例方法。非常感谢! – Andrew

+0

你能解释一下如何在类方法中使用自我单词?这是什么意思? – Andrew

+0

“在[method]实现中,'self'和'super'都指向接收对象,”请参见[Language Summary](http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual /ObjectiveC/Articles/ocLanguageSummary.html)在Apple的Objective-C书中。 – zoul