Get class type in shared objective-c method?

时间秒杀一切 提交于 2020-01-25 08:23:06

问题


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


回答1:


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];
}



回答2:


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



来源:https://stackoverflow.com/questions/3210101/get-class-type-in-shared-objective-c-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!