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

cocoa-touch, objective-c, objective-c-runtime

Solution

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

Problem

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) ```

Original source