iOS模型转字典模型转字典
//模型转字典
- (NSDictionary *)dicFromObject:(NSObject *)object {
NSMutableDictionary *dic = [NSMutableDictionary dictionary];
unsigned int count;
objc_property_t *propertyList = class_copyPropertyList([object class], &count);
for (int i = 0; i < count; i++) {
objc_property_t property = propertyList[i];
const char *cName = property_getName(property);
NSString *name = [NSString stringWithUTF8String:cName];
NSObject *value = [object valueForKey:name];//valueForKey返回的数字和字符串都是对象
if ([value isKindOfClass:[NSString class]] || [value isKindOfClass:[NSNumber class]]) {
//string , bool, int ,NSinteger
[dic setObject:value forKey:name];
} else if ([value isKindOfClass:[NSArray class]]) {
//数组或字典
[dic setObject:[self arrayWithObject:value] forKey:name];
} else if ([value isKindOfClass:[NSDictionary class]]) {
//数组或字典
[dic setObject:[self dicWithObject:value] forKey:name];
} else if (value == nil) {
//null
/
/[dic setObject:[NSNull null] forKey:name];//这⾏可以注释掉
} else {
//model
[dic setObject:[self dicFromObject:value] forKey:name];
}
}
return [dic copy];
}
//转数组
- (NSArray *)arrayWithObject:(id)object {
//数组
mutable是什么意思
NSMutableArray *array = [NSMutableArray array];
NSArray *originArr = (NSArray *)object;
if ([originArr isKindOfClass:[NSArray class]]) {
for (NSObject *object in originArr) {
if ([object isKindOfClass:[NSString class]]||[object isKindOfClass:[NSNumber class]]) {
//string , bool, int ,NSinteger
[array addObject:object];
} else if ([object isKindOfClass:[NSArray class]]) {
//数组或字典
[array addObject:[self arrayWithObject:object]];
} else if ([object isKindOfClass:[NSDictionary class]]) {
/
/数组或字典
[array addObject:[self dicWithObject:object]];
} else {
//model
[array addObject:[self dicFromObject:object]];
}
}
return [array copy];
}
py;
}
/
/转字典类型
- (NSDictionary *)dicWithObject:(id)object {
//字典
NSDictionary *originDic = (NSDictionary *)object;
NSMutableDictionary *dic = [NSMutableDictionary dictionary];
if ([object isKindOfClass:[NSDictionary class]]) {

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。