Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I get two different object instances 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) 
like image 917
Boon Avatar asked Apr 09 '13 15:04

Boon


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 a Class object is the same class, but the object_getClass of a Class is the meta class (the class of the class). This makes sense because a Class is an instance of the meta class, and according to documentation object_getClass returns “The class object of which object is an instance”. The output in LLDB would 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]; with NSObject *obj = [NSObject new];, the result will be the same when printing cls and cls2. That is,

    NSObject *obj = [NSObject new];
    Class cls = object_getClass(obj);
    Class cls2 = [obj class];
    NSLog(@"%p",cls);  // 0x7fff75f56840
    NSLog(@"%p",cls2); // 0x7fff75f56840
like image 164
Jano Avatar answered Nov 08 '22 21:11

Jano


The previous answer is right, but not the one for the asker.

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

When you add a 'KVO' to an instance, the instance is isa-swizzled. see Key-Value Observing Implementation Details

Some other libraries like ReactiveCocoa will also change an instance's 'isa' pointer. (Search 'RACSwizzleClass' in Source of ReactiveCocoa)

See also this blog(in Chinese):Class-swizzling, Isa-swizzling and KVO

like image 20
Dongle Avatar answered Nov 08 '22 22:11

Dongle