Reputation: 5101
I am getting an exception if a string is null:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSNull length]: unrecognized selector sent to instance
This is one of the objects of the dictionary,that contains a null string:
{
cabdriver = "<null>";
code = SV1000000079;
date = "2015-03-15";
destiny = "";
email = "[email protected]";
origin = vxd;
}
And this is my code where the exception is thrown:
- (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;
}
I have tried other ways to check if the string is null, but I have been searching and this should be the way to check it.
Please tell me what is wrong in my code?
Upvotes: 0
Views: 87
Reputation: 576
NSString *cabdriver = [[historialServicios objectAtIndex:indexPath.row] valueForKey:@"cabdriver"];
if ((NSNull *)cabdriver != [NSNull null])
{
cell.conductor_label.text = cabdriver;
}
else{
cell.conductor_label.text = @"-";
}
Upvotes: 1
Reputation: 989
Try using this once:
if (![cabdriver isKindOfClass:[NSNull class]])
{
cell.conductor_label.text = cabdriver;
}
Upvotes: 1
Reputation: 1840
When processing data returned from a server you should be prepared for any of the values to be null. I use the following two methods - one to check for a string, the other to check for a number:
- (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;
}
}
In the case of your cab driver, you could do the following:
NSString *cabDriver = [self stringValueOfDictionaryObject:(id)[[historialServicios objectAtIndex:indexPath.row] valueForKey:@"cabdriver"]];
Note that if your cab driver value is null in your json file, the routine above will return an empty string (@""). You could change that to @"-" either in the routine or after getting your cabDriver NSString value.
Upvotes: 1