Search code examples
iosobjective-cuilabelnsnull

How to deal with NSNull in my data?


I am getting an [NSNull rangeOfCharacterFromSet:]: exception when attempting to display a label. The error reads

'NSInvalidArgumentException', reason: '-[NSNull length]:

Below is my code.

UILabel* spousename = [[UILabel alloc] initWithFrame:CGRectMake(10,line, 300,20)];

[spousename setText:[_thisburial objectForKey:@"Spouse"]];

I tried to test for a null character with the following code but that didn't catch the error. It blew up when trying to execute the addSuview instruction.

if(![spousename isEqual:nil])
{
    [self.view addSubview:spousename];
}

So how do I test for NSNull in a label so I can prevent from getting this [NSNull rangeOfCharacterFromSet:]: error message?


Solution

  • Your data doesn't actually have a real value for "spouse" and this has been indicated by storing an instance of NSNull as the value. You need to check for this.

    This line:

    [spousename setText:[_thisburial objectForKey:@"Spouse"]];
    

    Should be updated to check the value. Something like this:

    id spouse = _thisburial[@"Spouse"];
    if ([spouse isKindOfClass:[NSString class]]) {
        spousename.text = spouse;
    } else {
        // The "spouse" value wasn't set or it's not a string
        spousename.text = @""; // Set to whatever you want here
    }