RickiG
RickiG

Reputation: 11390

Build a "printMe" method in to an Objective C class?

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:)

Upvotes: 0

Views: 127

Answers (1)

Max Seelemann
Max Seelemann

Reputation: 9364

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.

Upvotes: 1

Related Questions