Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS / Objective-C: Correct Way of Obtaining Meta Class Object

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.

  • The proper way to use those in different scenarios.
like image 284
Unheilig Avatar asked Jan 03 '14 11:01

Unheilig


2 Answers

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.

like image 67
simple_code Avatar answered Sep 20 '22 16:09

simple_code


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

like image 44
dehlen Avatar answered Sep 21 '22 16:09

dehlen