Le 19 avr. 2010 à 20:54, Greg Parker a écrit :

> On Apr 18, 2010, at 7:01 PM, Ken Thomases wrote:
>> On Apr 18, 2010, at 7:14 PM, Dave DeLong wrote:
>>> If I'm inside a method, is there a way to know at runtime whether that 
>>> method is a class or an instance method?
>> 
>> Keep in mind that class methods are just instance methods, where the 
>> instance is the class object.  (The class object being an instance of its 
>> metaclass.)
>> 
>> So, in a deep sense, there's no distinction between a class method and an 
>> instance method.  There's only the receiver object and the message/selector.
> 
> Absolutely correct. But in practice, you can distinguish between class and 
> instance methods everywhere except the root class.
> 
> The methods for a non-class instance are:
> * your class's instance methods
> * any superclass instance methods
> * NSObject's instance methods
> 
> The methods for a class instance are:
> * the class's class methods
> * any superclass class methods
> * NSObject's class methods
> * NSObject's instance methods
> 
> That last line is the weird one. It's caused by the twist at the top of the 
> instance/class/metaclass diagram that makes all class objects into instances 
> of their root class (usually NSObject). 
> http://sealiesoftware.com/blog/archive/2009/04/14/objc_explain_Classes_and_metaclasses.html
> 
> Comparing the two lists, you can see that the only overlap is NSObject's 
> instance methods. Everywhere else, you'll find that class methods are called 
> on class objects only, and instance methods are called on non-class objects 
> only. So "is self a class" will distinguish instance methods from class 
> methods, as long as you aren't writing instance methods on NSObject.
> 
> Note that `[self class] == self` is the wrong check. Some classes lie about 
> [self class]. One specific case is KVO. On some OS versions, KVO creates 
> subclasses of observed classes at runtime. The subclasses override accessor 
> methods to add willChange/didChange notifications. The KVO-generated 
> subclasses override [self class] to return the non-KVO superclass instead of 
> the KVO-generated subclass.

If the test was [self class] == MyClass.class, it would be wrong, but this is 
not what he does, and AFAIK, [self class] returns self only for class objects.

> You can use `object_getClass(self) == self` instead. object_getClass() never 
> lies.

It will never be true as this test is equivalent to self->isa == self, and isa 
is never self.


-- Jean-Daniel




_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to