扫码关注官方订阅号
我测试了一下 目前没有发现可以获取类别中属性的方法 以及途径 by runtime
业精于勤,荒于嬉;行成于思,毁于随。
获取property list:unsigned int count = 0;objc_property_t *properties = class_copyPropertyList([self class], &count);获取property名:const char *propertyName = property_getName(properties[index])使用KVC获取property值:id propertyValue = [self valueForKey:name];
unsigned int count = 0;
objc_property_t *properties = class_copyPropertyList([self class], &count);
const char *propertyName = property_getName(properties[index])
id propertyValue = [self valueForKey:name];
类别中的属性是关联对象,用key来获取。
- (NSArray *)allProperties { unsigned int count; // 获取类的所有属性 // 如果没有属性,则count为0,properties为nil objc_property_t *properties = class_copyPropertyList([self class], &count); NSMutableArray *propertiesArray = [NSMutableArray arrayWithCapacity:count]; for (NSUInteger i = 0; i < count; i++) { // 获取属性名称 const char *propertyName = property_getName(properties[i]); NSString *name = [NSString stringWithUTF8String:propertyName]; [propertiesArray addObject:name]; } // 注意,这里properties是一个数组指针,是C的语法, // 我们需要使用free函数来释放内存,否则会造成内存泄露 free(properties); return propertiesArray; }
- (NSDictionary *)allPropertyNamesAndValues { NSMutableDictionary *resultDict = [NSMutableDictionary dictionary]; unsigned int outCount; objc_property_t *properties = class_copyPropertyList([self class], &outCount); for (int i = 0; i < outCount; i++) { objc_property_t property = properties[i]; const char *name = property_getName(property); // 得到属性名 NSString *propertyName = [NSString stringWithUTF8String:name]; // 获取属性值 id propertyValue = [self valueForKey:propertyName]; if (propertyValue && propertyValue != nil) { [resultDict setObject:propertyValue forKey:propertyName]; } } // 记得释放 free(properties); return resultDict; }
更多细节可以看这篇文章中体验即可:点击进入
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部
获取property list:
unsigned int count = 0;objc_property_t *properties = class_copyPropertyList([self class], &count);获取property名:
const char *propertyName = property_getName(properties[index])使用KVC获取property值:
id propertyValue = [self valueForKey:name];类别中的属性是关联对象,用key来获取。
更多细节可以看这篇文章中体验即可:点击进入