stephen stephen - 2 months ago 16
iOS Question

Core Data - Iterating through the attributes of a NSManagedObject

I am a noob at core data, so here goes.

I have a core data object, for example student.

The student has mane attributes, like name, age, dob, address, and so on.

Now I need to display all these attributes into a table view.

Is there any easy way to iterate through the object student? Or do I have to convert the data into some type of dictionary?

If I need to convert it to a dictionary is there any support for it? Or do I have to write the function my self.

Many thanks for your help,
Stephen

Answer

Here's a very simple way to iterate over an NSManagedObject:

NSEntityDescription *entity = [myManagedObject entity];
NSDictionary *attributes = [entity attributesByName];
for (NSString *attribute in attributes) {
    id value = [myManagedObject valueForKey: attribute];
    NSLog(@"attribute %@ = %@", attribute, value);
}

The clues for how to do this (plus lots more) comes from Ole Bergmann's blog: http://oleb.net/blog/2011/05/inspecting-core-data-attributes/