Which from the following is the correct way of obtaining the meta class?
Class myMetaClass = objc_getMetaClass("NSString");
Or:
Class myMetaClass = object_getClass([NSString class]);
Are they both any different?
As mentioned in another post that is linked by the first answerer here:
Please tell me why objc_getMetaClass();
would break in certain cases in detail.
Both functions are correct, but objc_getMetaClass("NSString")
only works if NSString
is registered with the objective C runtime. Which it almost always is if you want to get its metaclass.
But if you're creating a class using Class myClass = objc_allocateClassPair(superClass,"my_own_class",0)
the situation is slightly different.
my_own_class
isn't registered yet, so if you need to access the metaclass (in order to add class methods), you must use object_getClass(myClass)
.
objc_getMetaClass("my_own_class")
would return nil
.
The difference is, that the second function returns the object for the named class and the second first the object for the metaclass of the named class... :)
Both of them call the class handler callback if the class is not registered to check a second time. When you call the metaclass function you WILL get a return result.
...(However, every class definition must have a valid metaclass definition, and so the metaclass definition is always returned, whether it’s valid or not.) from: Objective-C Runtime Reference
I think your real question is: What is the difference between a class and a metaclass ? Please have a look at this excellent explanation: What is meta-class in objective-c
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With