2

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 class 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 ?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Damn, i've written return [[[Base alloc] init] autorelease]; in instance method in my code. Thanks a lot!
Can you explain how can i use self word in a class method. What does it mean?
“Within the [method] implementation, both self and super refer to the receiving object,” see Language Summary in the Objective-C book by Apple.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.