Sometimes, the json object distributed by the backend does not have a key (a field is not distributed),
In this case, kvc is used to get the value of the object. Although no error will be reported (the Convention returns strings), in fact, a property value of the model object is nil
such as
UserInfo.h has an attribute @property (nonatomic, strong) NSString *userId; / / user ID //When the json object returned by the backend does not contain the userId field, //There is no error in kvc parsing, but the value of userinofa, userinofa.userid of UserInfo is nil //If userInofA.userId is inserted into a dictionary at this time, for example, the program will crash
Above, we need to detect the undelivered field (userId),
After kvc is executed, its nil value is changed to a meaningful value, such as "empty string"
Next, post a runtime method to poll all the properties of this class,
Reassign the attribute for nil to a meaningful string
#import "EPuserinfo.h"
#import <objc/runtime.h>
@implementation EPuserinfo
- (instancetype)initWithDict:(NSDictionary*)dict{
if ([super init]) {
//kvc
[self setValuesForKeysWithDictionary:dict];
//runtime checks for nil
[self checkKeysWithValues];
}
return self;
}
- (void)checkKeysWithValues {
unsigned int count ,i;
//Get property list array
objc_property_t *propertyArray = class_copyPropertyList([self class], &count);
for (i = 0; i < count; i++) {
objc_property_t property = propertyArray[i];
//Get property name string
NSString *proKey = [NSString stringWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
//Get the assignment corresponding to the property
id proValue = [self valueForKey:proKey];
if (proValue) {
//Reassign
[self setValue:proValue forKey:proKey];
} else {
//Value does not exist, prompt unKnown
[self setValue:@"unKnown" forKey:proKey];
}
}
free(propertyArray);
}
- (void)setValue:(id)value forUndefinedKey:(NSString *)key{
NSLog(@"EPuserinfo Class throws a key : %@",key);
}