在网络请求的结果block中,用lvc方法setValuesForKeysWithDictionary:给模型类对象mesInfo赋值。结果正常。
MPMesInfo *mesInfo = [[MPMesInfo alloc] init];
[mesInfo setValuesForKeysWithDictionary:snapshotDict];
[mesInfo setValuesForKeysWithDictionary:personDict];
[self.dataArr insertObject:mesInfo atIndex:0];
[self.tableView reloadData];
由于字典中层次复杂。为了简化,在模型类MPMesInfo中增加赋值方法
- (instancetype)initWithDict:(NSDictionary *)dict{
self = [super init];
if (self) {
NSArray *snapshotsArr = [dict[@"warnDetail"] valueForKey:@"snapshot"];
NSDictionary *snapshotDict = snapshotsArr[0];
NSArray *retsArr = [dict[@"warnDetail"] valueForKey:@"searchResult"];
NSDictionary *personDict = retsArr[0];
if (snapshotDict[@"cameraPlace"]) {
self.cameraPlace = snapshotDict[@"cameraPlace"];
}
self.snapshotTime = snapshotDict[@"snapshotTime"];
self.subImage = snapshotDict[@"subImage"];
self.image = personDict[@"image"];
self.score = personDict[@"score"];
}
return self;
}
- (void)setValue:(id)value forUndefinedKey:(NSString *)key{
}
结果,导致程序崩溃。
崩溃点:
tableview设置cell方法返回时。return时,崩溃。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *reusepool = @"reusePool";
MPMessageCell *cell = [tableView dequeueReusableCellWithIdentifier:reusepool];
if (cell == nil) {
cell = [[MPMessageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reusepool];
}
//真实数据
MPMesInfo *mesInfo = [self.dataArr objectAtIndex:indexPath.section];
[cell setMesInfo:mesInfo];
return cell;
}
控制台提示:
Fatal Exception: NSInvalidArgumentException
-[NSNull rangeOfCharacterFromSet:]: unrecognized selector sent to instance 0x19687eba0
崩溃原因:
json中有字段的值为null
https://stackoverflow.com/questions/27161914/ios-app-crash-on-startup
I have similar kind of problem. JSON response from sever contains NULL/null. Something like this:
"result":[
{
"id":"44",
"message":null,
}]
解决方案:
通过kvc中的方法去给模型类属性赋值,而不是用“=”赋值。
参考kvc:http://www.cnblogs.com/QianChia/p/5771049.html
修改如下:
- (instancetype)initWithDict:(NSDictionary *)dict{
self = [super init];
if (self) {
NSArray *snapshotsArr = [dict[@"warnDetail"] valueForKey:@"snapshot"];
NSDictionary *snapshotDict = snapshotsArr[0];
NSArray *retsArr = [dict[@"warnDetail"] valueForKey:@"searchResult"];
NSDictionary *personDict = retsArr[0];
[self setValuesForKeysWithDictionary:snapshotDict];
[self setValuesForKeysWithDictionary:personDict];
[self setValue:snapshotDict[@"image"] forKey:@"subImage"];
[self setValue:personDict[@"image"] forKey:@"searchedImage"];
// if (snapshotDict[@"cameraPlace"]) {
// self.cameraPlace = snapshotDict[@"cameraPlace"];
// }
// self.snapshotTime = snapshotDict[@"snapshotTime"];
// self.subImage = snapshotDict[@"subImage"];
//
// self.image = personDict[@"image"];
// self.score = personDict[@"score"];
}
return self;
}
//- (void)setValue:(id)value forKey:(NSString *)key{
//
//}
- (void)setValue:(id)value forUndefinedKey:(NSString *)key{
}
最后,那些空值以如下方式显示: