Objective-c class create methods
Let's say we have a class Base.
@inerface Base : NSObject
{
}
+(id) instance;
@end
@implementation Base
+(id) instance
{
return [[[self alloc] init] autorelease];
}
-(id) init
{
...
}
@end
And we have a derived class Derived.
@interface Derived : Base
{
}
@end
Which reimplements the init
method.
Now we want to create an instance of Derived class using class method +(id) instance
.
id foo = [Derived instance];
And now foo is actually a Base class.
How to achieve foo to be a Derived cla开发者_高级运维ss in this case?
Should I reimplement all the class method for derived classes ? (actually immplementation will be totally the same).
Is there a more elegant way ?
When you create an instance using [Derived instance]
, that instance will be of class Derived
. Try it. The trick is messaging self
in the instance
method:
+(id) instance
{
return [[[self alloc] init] autorelease];
}
When you send the instance
message to Base
, self
is Base
. When you send the same message to Derived
, self
is Derived
and therefore the whole thing works as desirable.
精彩评论