- (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;
}
网友评论