Core Data - Iterating through the attributes of a NSManagedObject

stephen picture stephen · Dec 11, 2011 · Viewed 11.7k times · Source

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

mpemburn picture mpemburn · Jul 3, 2012

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/