问题
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?
but "class_copyIvarList" isn't working on "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);
What is wrong with it?
回答1:
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.
来源:https://stackoverflow.com/questions/28301226/how-to-list-variables-for-nsmanagedobject