stephen stephen - 8 months ago 52
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,


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: