问题描述
我需要列出NSManagedObject的变量,我知道有一种方法使用class_copyIvarList,如
I needs to list variables for NSManagedObject, I know there is a way to do it using "class_copyIvarList" as given in How do I list all fields of an object in Objective-C?
但是class_copyIvarList对NSManagedObject不起作用。
but "class_copyIvarList" isn't working on "NSManagedObject".
这里是一段代码Im使用,它对NSObject NSManagedObject:
here is piece of code Im using, which is working perfectly fine for "NSObject" but not for "NSManagedObject":
unsigned int outCount;
Ivar *vars = class_copyIvarList([self class], &outCount);
for (int i = 0; i < outCount; i++) {
Ivar var = vars[i];
unsigned int idCount;
NSLog(@"%s %s", ivar_getName(var), ivar_getTypeEncoding(var));
}
free(vars);
它有什么问题?
推荐答案
我不知道你在这里做什么,但对于托管对象,它通常更典型的使用Core Data自己的内省,而不是问Objective-C运行时。在一个托管对象子类的方法中,你可以使用 [[self entity] propertiesByName]
来获取由实体类型定义的所有属性和关系的列表。您可以用 attributesByName
或 relationshipsByName
替换该方法,具体取决于您需要什么。您可以进一步查询您获取的对象,例如查找属性或关系的目标实体的类型。
I'm not sure what you're doing here, but with managed objects it's usually more typical to use Core Data's own introspection rather than ask the Objective-C runtime. In a method on a managed object subclass, you'd use [[self entity] propertiesByName]
to get a list of all attributes and relationships defined by the entity type. You could replace that method with attributesByName
or relationshipsByName
depending on what you need. The objects you get back can be further queried, for example to find out the type of a property or the target entity of a relationship.
这篇关于如何列出NSManagedObject的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!