Object_getClass (obj) and [obj class] give different results

I get two different instances of the object when calling object_getClass (obj) and [obj class]. Any idea why?

Class cls = object_getClass(obj); Class cls2 = [obj class]; (lldb) po cls $0 = 0x0003ca00 Test (lldb) po cls2 $1 = 0x0003ca14 Test (lldb) 
+4
source share
2 answers

I suspect that obj, despite the name, is a class. Example:

 Class obj = [NSObject class]; Class cls = object_getClass(obj); Class cls2 = [obj class]; NSLog(@"%p",cls); // 0x7fff75f56840 NSLog(@"%p",cls2); // 0x7fff75f56868 

The reason is that the class of the class object is the same class, but the object_getClass class is a meta-class (class of the class). This makes sense because the class is an instance of the metaclass, and according to the documentation object_getClass returns "The object of the class whose instance the object is." The result in LLDB will be:

 (lldb) p cls (Class) $0 = NSObject (lldb) p cls2 (Class) $1 = NSObject (lldb) po cls $2 = 0x01273bd4 NSObject (lldb) po cls2 $3 = 0x01273bc0 NSObject 

If you replace Class obj = [NSObject class]; on NSObject *obj = [NSObject new]; , the result will be the same when printing cls and cls2. I.e

  NSObject *obj = [NSObject new]; Class cls = object_getClass(obj); Class cls2 = [obj class]; NSLog(@"%p",cls); // 0x7fff75f56840 NSLog(@"%p",cls2); // 0x7fff75f56840 
+8
source

The previous answer is correct, but not the one that asks the question.

For an instance (not a class), the only reason object_getClass (obj) and [obj class] are different is isa-swizzling or some other swizzling that changes the pointer to the isa instance.

When you add "KVO" to an instance, the instance is is-swizzled. see Monitoring Key Values

Some other libraries, such as ReactiveCocoa, will also change the isa pointer. (Search for "RACSwizzleClass" in ReactiveCocoa Source )

+2
source

All Articles