Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 906
LombaX Avatar asked Apr 30 '13 16:04

LombaX


2 Answers

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 .

like image 125
Ramy Al Zuhouri Avatar answered Nov 09 '22 15:11

Ramy Al Zuhouri


Since you are using lldb, you may want to try

_ivarDescription
_propertyDescription
_methodDescription
_shortMethodDescription

You can use them with po when you hit a breakpoint

po [yourObject _ivarDescription]
like image 20
xi.lin Avatar answered Nov 09 '22 14:11

xi.lin