如何打印NSObject的所有声明属性的值?

时间:2022-10-03 20:11:00

I want to override my object's description method to be able to print the values of all my declared properties. I know that I can do this by appending all the values to each other, one by one, but sometimes this is time consuming if you have a lot of properties.

我想覆盖我的对象的描述方法,以便能够打印我所有声明的属性的值。我知道我可以通过逐个附加所有值来实现这一点,但是如果你有很多属性,有时这很费时间。

I was wondering if there's an easy way to do this, by getting help from the runtime powers of Objective-C?

通过从Objective-C的运行时功能获得帮助,我想知道是否有一种简单的方法可以做到这一点?

1 个解决方案

#1


6  

Did you try this solution ?

你试过这个解决方案吗?

#import <Foundation/Foundation.h>
#import <objc/runtime.h>

@interface NSObject (PropertyListing)

// aps suffix to avoid namespace collsion
//   ...for Andrew Paul Sardone
- (NSDictionary *)properties_aps;

@end

@implementation NSObject (PropertyListing)

- (NSDictionary *)properties_aps {
    NSMutableDictionary *props = [NSMutableDictionary dictionary];
    unsigned int outCount, i;
    objc_property_t *properties = class_copyPropertyList([self class], &outCount);
    for (i = 0; i < outCount; i++) {
        objc_property_t property = properties[i];
        NSString *propertyName = [[[NSString alloc] initWithCString:property_getName(property)] autorelease];
        id propertyValue = [self valueForKey:(NSString *)propertyName];
        if (propertyValue) [props setObject:propertyValue forKey:propertyName];
    }
    free(properties);
    return props;
}

@end

#1


6  

Did you try this solution ?

你试过这个解决方案吗?

#import <Foundation/Foundation.h>
#import <objc/runtime.h>

@interface NSObject (PropertyListing)

// aps suffix to avoid namespace collsion
//   ...for Andrew Paul Sardone
- (NSDictionary *)properties_aps;

@end

@implementation NSObject (PropertyListing)

- (NSDictionary *)properties_aps {
    NSMutableDictionary *props = [NSMutableDictionary dictionary];
    unsigned int outCount, i;
    objc_property_t *properties = class_copyPropertyList([self class], &outCount);
    for (i = 0; i < outCount; i++) {
        objc_property_t property = properties[i];
        NSString *propertyName = [[[NSString alloc] initWithCString:property_getName(property)] autorelease];
        id propertyValue = [self valueForKey:(NSString *)propertyName];
        if (propertyValue) [props setObject:propertyValue forKey:propertyName];
    }
    free(properties);
    return props;
}

@end