Search code examples
objective-cdebugginggdblldb

debug: Obtain a list of all instance variables of an object (unknown type)


Is there any method to obtain (via debug) a list of all instance variables of an unknown object in Objective-c?

I use lldb for debug, but I admit that I don't know it very well.

Obviously I can't look at the header of this unknown object.

I need to do it at debug time, but if it's not possible I can use an alternative at runtime.

I've found this post: How do I list all fields of an object in Objective-C? but, as I understand, I need to have a known Class (I need the headers of the object)

Any suggestion?


Solution

  • Exploiting the code of the accepted answer of the question that you linked, the only thing that you need to do is to wrap it into a convenient method, so that you could call it at any time during debug. At your place I would write a category extending NSObject, adding a method that returns a NSDictionary with all the ivars; Here is an example:

    - (NSDictionary*) ivars
    {
        NSMutableDictionary* ivarsDict=[NSMutableDictionary new];
        unsigned int count;
        Ivar* ivars=class_copyIvarList([self class], &count);
        for(int i=0; i<count; i++)
        {
            Ivar ivar= ivars[i];
            const char* name = ivar_getName(ivar);
            const char* typeEncoding = ivar_getTypeEncoding(ivar);
            [ivarsDict setObject: [NSString stringWithFormat: @"%s",typeEncoding] forKey: [NSString stringWithFormat: @"%s",name]];
        }
        free(ivars);
        return ivarsDict;
    }
    

    Then given that object of which you don't know the type, if it directly or indirectly inherits from NSObject you just need to print the dictionary returned from this method:

    (lldb) po [someObject ivars]
    

    Credits: How do I list all fields of an object in Objective-C?

    PS: You need to import objc/runtime.h .