0

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?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Dave
  • 873
  • 2
  • 15
  • 27

2 Answers2

1

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
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
0

[_thisburial objectForKey:@"Spouse"] is returning an NSNull. There needs to be special handing for this.

NSString *spouseString = [_thisburial objectForKey:@"Spouse"];
if (spouseString == (id)[NSNull null]) {
    spouseString = @"";
}

[spousename setText:spouseString];
Jeffery Thomas
  • 42,202
  • 8
  • 92
  • 117
  • Thanks for the suggestion. I had to use if ([spouseString isEqual: [NSNull null]]) and that worked. – Dave Apr 22 '16 at 17:25
  • Sorry! The spouseString == [NSNull null] didn't work! It didn't recognize the null. – Dave Apr 22 '16 at 17:30
  • I tested your suggestion again using f ([spouseString.text isEqual: [NSNull null]]) and that worked also. The key problem was that I wasn't using the text suffix on the variable. – Dave Apr 22 '16 at 17:45
  • @Dave that odd `spouseString.text` should crash. Neither `NSString` nor `NSNull` has a property `text`. – Jeffery Thomas Apr 23 '16 at 11:57
  • It really doesn't matter. @rmaddy has a better answer. – Jeffery Thomas Apr 23 '16 at 11:58