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

偶尔善良 提交于 2019-12-03 03:37:57
Ramy Al Zuhouri

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 .

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]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!