#import "NSObject+PropertyList.h"
#import <objc/runtime.h>
@implementation NSObject (PropertyList)
// 獲取屬性列表 在字典轉(zhuǎn)模型的時候非常有用
+ (instancetype)objWithDict:(NSDictionary *)dict {
id instance = [[self alloc]init];
[[self propertys] enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
id value = dict[obj];
if (value) {
// 設(shè)置屬性值
[instance setValue:value forKey:obj];
}
}];
return instance;
}
// copy, create,retain
+ (NSArray *)propertys {
unsigned int count;// 表示屬性個數(shù)
// 獲取到所有的屬性
objc_property_t *list = class_copyPropertyList(self, &count); // 數(shù)組
NSMutableArray *data = [NSMutableArray array];
for (int i = 0; i < count; ++i) {
// 取出每一個屬性
objc_property_t key = list[i];
// 轉(zhuǎn)成字符串
NSString *propertyName = [[NSString alloc]initWithCString:property_getName(key) encoding:NSUTF8StringEncoding];
// NSLog(@"%@",propertyName);
[data addObject:propertyName];
}
// 釋放list
free(list);
return data.copy;
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。