工具类:快速字典转模型(NSObject 分类/runtime 用法2:获取属性列表)

来源:互联网 发布:网络交换机设置 编辑:程序博客网 时间:2024/06/06 11:39
#import <Foundation/Foundation.h>@interface NSObject (PropertyList)// 通过一个字典创建一个模型+ (instancetype)objWithDict:(NSDictionary *)dict;@end#import "NSObject+PropertyList.h"#import <objc/runtime.h>@implementation NSObject (PropertyList)// 获取属性列表 在字典转模型的时候非常有用+ (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) {            // 设置属性值            [instance setValue:value forKey:obj];        }    }];    return instance;}// copy, create,retain+ (NSArray *)propertys {    unsigned int count;// 表示属性个数    // 获取到所有的属性    objc_property_t *list = class_copyPropertyList(self, &count); // 数组    NSMutableArray *data = [NSMutableArray array];    for (int i = 0; i < count; ++i) {        // 取出每一个属性        objc_property_t key = list[i];        // 转成字符串        NSString *propertyName = [[NSString alloc]initWithCString:property_getName(key) encoding:NSUTF8StringEncoding];        //        NSLog(@"%@",propertyName);        [data addObject:propertyName];    }    // 释放list    free(list);    return data.copy;}@end
0 0
原创粉丝点击