如何在Objective-C中列出对象的所有字段? [英] How do I list all fields of an object in Objective-C?
本文介绍了如何在Objective-C中列出对象的所有字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有一个类,如何列出其所有的实例变量名称?
例如:
@interface MyClass:NSObject {
int myInt;
NSString * myString;
NSMutableArray * myArray
}
我想获得myInt,myString和myArray 。有没有办法可能得到一个名字数组,我可以迭代?
我试过搜索Objective-C文档但找不到任何东西(我也不确定是什么)。
$如上所述,您可以使用Objective-C运行时API来检索实例变量名称:$ b b
unsigned int varCount;
Ivar * vars = class_copyIvarList([MyClass class],& varCount);
for(int i = 0; i Ivar var = vars [i];
const char * name = ivar_getName(var);
const char * typeEncoding = ivar_getTypeEncoding(var);
//做你想要的名字和类型
}
free(vars);
If I have a class, how can I list all its instance variable names?
eg:
@interface MyClass : NSObject {
int myInt;
NSString* myString;
NSMutableArray* myArray;
}
I would like to get "myInt", "myString", and "myArray". Is there some way to perhaps get an array of names that I can iterate over?
I've tried searching the Objective-C documentation but couldn't find anything (and I'm not sure what this is called either).
解决方案
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);
这篇关于如何在Objective-C中列出对象的所有字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文