tags:

views:

26

answers:

1

Hi

I have some Entities holding values for my program. E.g. a "Person" Entity has synthesized properties for the values "name", "age", "address" etc.

I wish to build a "printMe" method on the Entity, so that invoking this method results in the above properties being printed to the console like "\nPropertyName:Value".

I have done this with Core Data Entities before by using something like this:

- (void) printMe {

NSEntityDescription *entity = [NSEntityDescription entityForName:@"NewAirline" inManagedObjectContext:[self managedObjectContext]];

for (NSString *attr in [entity attributesByName]) {
    //[object setValue:@"n/a" forKey:attr];

    NSLog(@"%@:%@", attr, [self valueForKey:attr]);
}
NSLog(@"*************** end ***************\n");    

}

The Entity I have in this case is not Core Data and I can't use attributesByName. But it should still be key-value compliant so I guess there is a way around this.

My Entity has 20+ properties and I would like to avoid doing it manual by listing each property and calling it by name in NSLog.

Thanks in advance for any help given:)

+1  A: 

You can use the Objective-C runtime Api. The function class_copyPropertyList gives you all declared properties of a given class. You can then get their names etc using more runtime functions like property_getAttributes or property_getName. Using that name you can access the value in a KVC-compliant manner.

Max Seelemann
Thank you Max. I am not that familiar with the runtime API, your help gave me enough to figure it out. I am going to mix your answer and Franks comment:)
RickiG