如何打印NSObject的所有已声明属性的值? [英] How do I print the values of all declared properties of an NSObject?

查看:148
本文介绍了如何打印NSObject的所有已声明属性的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想重写对象的描述方法,以便能够打印所有声明的属性的值.我知道我可以通过将所有值一个接一个地附加在一起来做到这一点,但是有时候如果您有很多属性,这会很耗时.

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.

我想知道是否可以通过从Objective-C的运行时功能获得帮助来实现此目的?

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

推荐答案

您尝试过此解决方案?

#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

这篇关于如何打印NSObject的所有已声明属性的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆