如果字符串为null,我将收到异常:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSNull length]: unrecognized selector sent to instance
这是字典的一个对象,它包含一个空字符串:
{
cabdriver = "<null>";
code = SV1000000079;
date = "2015-03-15";
destiny = "";
email = "jose@gmail.com";
origin = vxd;
}
这是我抛出异常的代码:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
HistorialCellTableViewCell *cell = (HistorialCellTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"Cell"];
NSString *origin = [[historialServicios objectAtIndex:indexPath.row] valueForKey:@"origin"];
if (origin.length ==0){
cell.origen_label.text = @"-";
} else {
cell.origen_label.text = origin;
}
NSString *destiny = [[historialServicios objectAtIndex:indexPath.row] valueForKey:@"destiny"];
if (destiny.length ==0){
cell.destiny_label.text = @"-";
} else {
cell.destiny_label.text = destiny;
}
NSString *cabdriver = [[historialServicios objectAtIndex:indexPath.row] valueForKey:@"cabdriver"];
if (cabdriver.length ==0){
cell.conductor_label.text = @"-";
} else {
cell.conductor_label.text = cabdriver;
}
NSString *date = [[historialServicios objectAtIndex:indexPath.row] valueForKey:@"date"];
cell.fecha_label.text = date;
return cell;
}
我已经尝试过其他方法来检查字符串是否为空,但我一直在搜索,这应该是检查它的方法。
请告诉我我的代码有什么问题?
答案 0 :(得分:2)
NSString *cabdriver = [[historialServicios objectAtIndex:indexPath.row] valueForKey:@"cabdriver"];
if ((NSNull *)cabdriver != [NSNull null])
{
cell.conductor_label.text = cabdriver;
}
else{
cell.conductor_label.text = @"-";
}
答案 1 :(得分:1)
尝试使用一次:
if (![cabdriver isKindOfClass:[NSNull class]])
{
cell.conductor_label.text = cabdriver;
}
答案 2 :(得分:1)
处理从服务器返回的数据时,您应该准备好将任何值设为null。我使用以下两种方法 - 一种检查字符串,另一种检查数字:
- (NSString *)stringValueOfDictionaryObject:(id)dictionaryObject
{
if (dictionaryObject == [NSNull null]) {
return @"";
}
else {
return (NSString *)dictionaryObject;
}
}
- (NSNumber *)numericValueOfDictionaryObject:(id)dictionaryObject
{
if (dictionaryObject == [NSNull null]) {
return nil;
}
else {
return (NSNumber *)dictionaryObject;
}
}
对于您的出租车司机,您可以执行以下操作:
NSString *cabDriver = [self stringValueOfDictionaryObject:(id)[[historialServicios objectAtIndex:indexPath.row] valueForKey:@"cabdriver"]];
请注意,如果json文件中的cab驱动程序值为null,则上面的例程将返回一个空字符串(@&#34;&#34;)。您可以将其更改为@&#34; - &#34;在例程中或在获取cabDriver NSString值之后。