Frage

In Objective-C, how does one obtain the metaclass object? Both [self class] and [ClassName class] returns the Class object only.

War es hilfreich?

Lösung

objc_getMetaClass

Edit: Improved as per Greg's suggestion in the comments.

object_getClass([Class class]);

Andere Tipps

object_getClass([self class])
object_getClass([ClassName class])

You'll probably have to use the objective-C runtime function object_getClass to get the class of the class object.

A good write up What is a meta-class in Objective-C goes through some detail on meta-classes. However, in some cases the class of the meta-class is the class itself.

Do you wish to obtain information for the purposes of meta-programming / reflection?

This information is available via a plain-C API.

Unlike some other object-oriented languages, the meta-class itself is pretty thin on information, with other C functions filling in the details.

If you're new to Objective-C, C and C++ it might be easier to use Mike Ash's Objective-C wrapper library.

You can get the metaclass for an object via

[[self class] class]

The [self class] yields a pointer to the Class object (i.e. what the isa pointer points to). Since this is an object with a class as well, you can follow the isa pointer again to get the metaclass.

You can find a diagram (http://www.sealiesoftware.com/blog/class%20diagram.pdf) in this blog post (http://www.sealiesoftware.com/blog/archive/2009/04/14/objc_explain_Classes_and_metaclasses.html) an another post that explain it differently. Sorry for the weird links but I had to get past the reputation filter...

I would be curious to know why you would want a pointer to the metaclass though...

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top