问题
In Objective-C
, how does one obtain the metaclass object? Both [self class]
and [ClassName class]
returns the Class object only.
回答1:
objc_getMetaClass
Edit: Improved as per Greg's suggestion in the comments.
object_getClass([Class class]);
回答2:
object_getClass([self class])
object_getClass([ClassName class])
回答3:
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.
回答4:
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.
回答5:
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...
来源:https://stackoverflow.com/questions/20833144/in-objective-c-how-to-obtain-the-metaclass-object