有时候后端下发的json对象并不存在某个key(某个字段没有下发),
这时候使用kvc去获取对象的值,虽然不会报错(约定均返回字符串),但实际此model对象的某个属性值是为nil的
比如
UserInfo.h 有个属性
@property (nonatomic, strong) NSString *userId;//用户ID
//当后端返回的json对象中不包含 userId 字段时,
//kvc解析不会报错, 但是 UserInfo的对象 userInofA, userInofA.userId的值是为nil.
//若此时,将userInofA.userId塞入一个字典中,比如会导致程序崩溃.
以上, 就需要我们检测出这个未下发的字段(userId),
并且在kvc执行之后,将其nil的值修改为一个有意义的值,比如” “空字符串之类的.
下面,贴出一个runtime方法,轮询出本类的所有属性,
对为nil的属性重新赋值为有意义的字符串
#import "EPuserinfo.h"
#import <objc/runtime.h>
@interface EPuserinfo()
{
NSString *status_proValue; //statues字段的值
}
@end
@implementation EPuserinfo
- (instancetype)initWithDict:(NSDictionary*)dict{
if ([super init]) {
//kvc
[self setValuesForKeysWithDictionary:dict];
//runtime检测是否有nil
[self checkKeysWithValues];
}
return self;
}
- (void)checkKeysWithValues {
unsigned int count ,i;
//1.文档字段赋值
//获取属性列表数组
objc_property_t *propertyArray = class_copyPropertyList([self class], &count);
for (i = 0; i < count; i++) {
objc_property_t property = propertyArray[i];
//获取属性名称字符串
NSString *proKey = [NSString stringWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
//获取属性对应的赋值
id proValue = [self valueForKey:proKey];
if (proValue) {
//将非字符串数据转换为NSString
if (![proValue isKindOfClass:[NSString class]]) {
proValue = [NSString stringWithFormat:@"%@",proValue];
}
//重新赋值
[self setValue:proValue forKey:proKey];
//获取statues字段的value
if ([proKey isEqualToString:@"status"]) {
status_proValue = proValue;
}
} else {
//值不存在,提示unKnown
[self setValue:@"unKnown" forKey:proKey];
}
}
free(propertyArray);
//2.非文档字段(statusDec)-转码
[self setDecValueForKey_StatusDec:@"statusDec"];
}
#pragma mark statusDec字段(非文档)赋值转码
- (void)setDecValueForKey_StatusDec:(NSString*)proKey{
if ([status_proValue isEqualToString:@"0"]) {
[self setValue:@"审核通过" forKey:proKey];
}
if ([status_proValue isEqualToString:@"1"]) {
[self setValue:@"待审核" forKey:proKey];
}
if ([status_proValue isEqualToString:@"2"]) {
[self setValue:@"审核失败" forKey:proKey];
}
if ([status_proValue isEqualToString:@"9"]) {
[self setValue:@"审核作废" forKey:proKey];
}
}