美文网首页
简单字典模型互转

简单字典模型互转

作者: zzL丶 | 来源:发表于2019-12-12 11:36 被阅读0次
- (instancetype)initWithDic:(NSDictionary *)dic {
    if (self = [super init]) {
        for (NSString *key in dic.allKeys) {
            id value = dic[key];
            NSString *methodName = [NSString stringWithFormat:@"set%@:",key.capitalizedString];
            SEL sel = NSSelectorFromString(methodName);
            if (sel) {
                ((void(*)(id, SEL, id))objc_msgSend)(self, sel, value);
            }
        }
    }
    return self;
}
- (NSDictionary *)toDic {
    unsigned int count = 0;
    objc_property_t *properties = class_copyPropertyList((id)self.class, &count);
    if (count != 0) {
        NSMutableDictionary *tempDic = [NSMutableDictionary dictionary];
        for (int i = 0; i < count; i++) {
            const void *propertyName = property_getName(properties[i]);
            NSString *name = [NSString stringWithUTF8String:propertyName];
            SEL sel = NSSelectorFromString(name);
            if (sel) {
                id value = ((id(*)(id, SEL))objc_msgSend)(self, sel);
                //可截取变量类型
                const char *type = property_getAttributes(properties[i]);
                NSString *typeStr = [NSString stringWithUTF8String:type];
                NSLog(@"%@   %@", name, typeStr);
                if (value) {
                    [tempDic setValue:value forKey:name];
                }else {
                    [tempDic setValue:@"" forKey:name];
                }
            }
        }
        free(properties);
        return tempDic;
    }
    free(properties);
    return nil;
}

相关文章

网友评论

      本文标题:简单字典模型互转

      本文链接:https://www.haomeiwen.com/subject/scozgctx.html