Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Print out(NSLog) the properties of a custom object added to a NSMutableArray

I have a custom object that I create with 3 properties defined in it. I create the object and assign the values to those properties. After that I put that object into an NSMutable Array. I know I can use :

for (id obj in personArray)
{
             NSLog(@"obj: %@", obj);
}
NSLog(@"%@", personArray);

To tell me what kind of objects are in my array. But I want to go a level deeper, I want to be able to see what the properties are for each of those objects. I'm just not sure how to target them.

Here is the code and I am using: Person is my custom object.

personObject = [[Person alloc]init];
[personObject setFirstName:firstName.text];
[personObject setLastName:lastName.text];
[personObject setEmail:emailAddress.text];

// add the person object to the array
// the array was alloc and init in a method above this code.
[personArray addObject:personObject];

for (id obj in personArray)
{
    NSLog(@"obj: %@", obj);
}

NSLog(@"%@", personArray);
like image 371
icekomo Avatar asked Oct 12 '13 23:10

icekomo


2 Answers

To print all the properties of one object, use followed codes:

- (void) logProperties:(NSObject*)obj {

NSLog(@"----------------------------------------------- Properties for object %@", obj);

    unsigned int numberOfProperties = 0;
    objc_property_t *propertyArray = class_copyPropertyList([obj class], &numberOfProperties);
    for (NSUInteger i = 0; i < numberOfProperties; i++) {
        objc_property_t property = propertyArray[i];
        NSString *name = [[NSString alloc] initWithUTF8String:property_getName(property)];
        NSLog(@"Property %@ Value: %@", name, [self valueForKey:name]);
    }
NSLog(@"-----------------------------------------------");
}
like image 149
lbsweek Avatar answered Oct 19 '22 01:10

lbsweek


There is a simple way than using description method in all classes.

Use ICHObjectPrinter:

NSLog(@"Object description is %@",[ICHObjectPrinter descriptionForObject:person]);

https://github.com/arundevma/ICHObjectPrinter

like image 36
arundevma Avatar answered Oct 19 '22 00:10

arundevma