Is there a way to log all the property values of an Objective-C instance

前端 未结 5 1650
庸人自扰
庸人自扰 2021-02-04 03:22

I was just wondering if there is a quick and easy way of printing out to the log all of the various values of the properties to my class for debugging purposes. Like I would lik

5条回答
  •  北荒
    北荒 (楼主)
    2021-02-04 03:45

    This question seems the have the answer to your question.

    Update:

    I got curious and made a catagory:

    //Using Xcode 4.5.2 - iOS 6 - LLDB - Automatic Reference Counting
    
    //NSObject+logProperties.h    
    @interface NSObject (logProperties)
    - (void) logProperties;
    @end
    
    //NSObject+logProperties.m
    #import "NSObject+logProperties.h"
    #import 
    
    @implementation NSObject (logProperties)
    
    - (void) logProperties {
    
        NSLog(@"----------------------------------------------- Properties for object %@", self);
    
        @autoreleasepool {
            unsigned int numberOfProperties = 0;
            objc_property_t *propertyArray = class_copyPropertyList([self 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]);
            }
            free(propertyArray);
        }    
        NSLog(@"-----------------------------------------------");
    }
    
    @end
    

    Include it in your class: #import "NSObject+logProperties.h"

    and call [self logProperties]; to those properties!

提交回复
热议问题