【问题标题】:How do I print the values of all declared properties of an NSObject?如何打印 NSObject 的所有声明属性的值?
【发布时间】:2012-12-02 14:41:48
【问题描述】:

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

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

【问题讨论】:

    标签: iphone objective-c ios runtime


    【解决方案1】:

    你试过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
    

    【讨论】:

    • 实际上我已经看到了那个网页,但我无法向下滚动源代码,可能是由于我的浏览器的问题。原作者应该更好地以不同的方式显示该代码,以便像我这样的人不会放弃:) 谢谢!
    • 我在我的项目中使用了 obj_runtime。但是其中一个项目被客户拒绝了,他说这就像黑客攻击!我不想透露他们的名字。 “大炮”的名字你一定猜到了。
    • 嗯,你这么说很好。我只是在开发时将其用于调试目的。我最好在发布应用程序之前删除该部分。谢谢!
    • 原始数据类型的属性呢?
    • 我发现这段代码对于在我的视图层上快速查找数据很有用。例如,当添加 CAKeyframeAnimation 来更改图层的不透明度时,我发现它会更改 UIView 图层的presentationLayer。如果不使用上面的类别代码,我不会发现这一点,它不仅对调试非常有用,而且对了解更多我通常认为理所当然的事情很有用。
    猜你喜欢
    • 2011-03-03
    • 1970-01-01
    • 2018-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-20
    • 2015-11-17
    • 1970-01-01
    相关资源
    最近更新 更多