ghostrider
ghostrider

Reputation: 5259

NSNull isEqualToString: unrecognized selector on ObjC

Well my code was like this:

I have two strings, place and date. I am using them like this:

cell.datePlace.text= [NSString stringWithFormat:@"%@, %@",date,place];

In some entries, the output is like this:

"21/10/2012, <null>"
"21/11/2012, None"
"21/12/2013, London"

My app does not crash but I want the place to be visible only when is not null and not equal to None.

So I tried this:

 NSString * place=[photo objectForKey:@"place"];


if ([place isEqualToString:@"None"]) {
                cell.datePlace.text= [NSString stringWithFormat:@"%@",date];
            } else {
                cell.datePlace.text= [NSString stringWithFormat:@"%@, %@",date,place];
            }

Problem was when place was <null> my app crashed and I got this error:

[NSNull isEqualToString:] unrecognized selector send to instance

So, i tried this:

if (place) {
            if ([place isEqualToString:@"None"]) {
                cell.datePlace.text= [NSString stringWithFormat:@"%@",date];
            } else {
                cell.datePlace.text= [NSString stringWithFormat:@"%@, %@",date,place];
            }
        } else {
            cell.datePlace.text= [NSString stringWithFormat:@"%@",date];
        }

But the problem remains.

Upvotes: 7

Views: 6080

Answers (3)

Kjuly
Kjuly

Reputation: 35181

Use

if (! [place isKindOfClass:[NSNull class]) {
  ...
}

instead of

if (place) {
   ...
}

Note: NSNull object is not nil, so the if (place) will be true then.

Upvotes: 4

Wain
Wain

Reputation: 119041

I guess your source data is coming from JSON or similar (something where data is being parsed in and missing data is being set to NSNull). It's the NSNull that you need to deal with and aren't currently.

Basically:

if (place == nil || [place isEqual:[NSNull null]]) {
    // handle the place not being available 
} else {
    // handle the place being available
}

Upvotes: 31

RFG
RFG

Reputation: 2902

Use [NSNull null]:

if ([place isKindOfClass:[NSNull class]])
{
    // What happen if place is null

}

Upvotes: 3

Related Questions