views:

25

answers:

2

In Objective-C there is the Alloc/Init metaphor. They've also added a shared convenience method called 'new' that internally just calls both in succession. And if I create a subclass of NSObject called FooClass, FooClass picks up those shared methods, including 'new'.

BUT... how the heck is that implemented??

It can't simply delegate to the base class because that would just instantiate an instance of NSObject, not your derived class FooClass, yet it still works! So how would someone write something similar?

In other words, the base class shouldn't be this...

  + (id) somethingLikeNew{
        return [[NSObject alloc] init];  
    }

But rather this...

  + (id) somethingLikeNew{
        return [[<SomethingThatMapsToFooClassType> alloc] init];  
    }

...where 'SomethingThatMapsToFooClassType' is the type of the derived class that inherits from NSObject and which needs to pick up the shared method 'somethingLikeNew'.

Basically I'm adding a category off of NSObject and I have shared methods that need to know the type, but the implementations are all generic, hence going in a category on NSObject and not all over the place in my class files (the same way you don't have 'new' all over the place. It's just there.)

Anyone? Bueller? Bueller?

M

A: 

Ha! Found it myself two seconds after posting this! You can use 'self' in a shared method to represent the class type for the derived class, so the above would simply be...

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

Damn, that was easy! Hope this helps someone else!

M

MarqueIV
+6  A: 

Within any Objective-C method, the self (implicit) parameter refers to the receiver. In the case of a class method, self is the Class object. So polymorphic class methods can be implemented like

+ (id)somethingLikeNew
{
   return [[self alloc] init];
}
Barry Wark
Lol... I guess we posted at the same time. I just said that myself!
MarqueIV
It's always best when you figure out the answer yourself. Good job.
Barry Wark