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

感情迁移 提交于 2019-11-28 13:22:42

You have to use the description method inside your Person class

-(NSString *)description{

    return @"FirstName: %@, LastName: %@, E-mail: %@", 
                        _firstName, _lastName, _email;
}

This way you can print always the object you have inside your NSArray but instead of the memory description you'll get returned the values you've defined before in your description method of the specific object.

If you just want to do this with the element from the NSArray use placeholders:

NSLog(@"FirstName: %@, LastName: %@, E-mail: %@", 
                       obj.firstname, obj.lastname, obj.email);

There is not much difference between, but its more useful because you don't have to rewrite it once you have created your description method, you just have to print the object.

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

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(@"-----------------------------------------------");
}
BTSmith

For a slightly more advanced solution check out this answer https://stackoverflow.com/a/2304797/519280. You can add this code to a base class that your Person object extends, and from then on you can use the autoDescribe function to automatically print out all the properties of your object without having to go through the process of manually listing all the properties in the describe method.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!