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

喜欢而已 提交于 2019-11-27 13:33:33

As mentioned, you can use the Objective-C runtime API to retrieve the instance variable names:

unsigned int varCount;

Ivar *vars = class_copyIvarList([MyClass class], &varCount);

for (int i = 0; i < varCount; i++) {
    Ivar var = vars[i];

    const char* name = ivar_getName(var);
    const char* typeEncoding = ivar_getTypeEncoding(var);

    // do what you wish with the name and type here
}

free(vars);
Abhishek Bedi
#import <objc/runtime.h>


NSUInteger count;
Ivar *vars = class_copyIvarList([self class], &count);
for (NSUInteger i=0; i<count; i++) {
    Ivar var = vars[i];
    NSLog(@"%s %s", ivar_getName(var), ivar_getTypeEncoding(var));
}
free(vars);

Consider gen_bridge_metadata, which is intended for a completely different purpose, but can produce XML files from Objective-C header files.

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