gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 03:52:31 25 4
gpt4 key购买 nike

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

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

最佳答案

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

关于iphone - 如何打印 NSObject 的所有已声明属性的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13881353/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com