3

jI am building an app where I want to show cleaner's contact information in a UIButton if a cleaner has been assigned to a job, and not show that UIButton otherwise. I have "appointment" objects that have cleaner and cleanerPhone strings as properties. I tried using this to check whether to print string:

if(appt.cleanerPhone)

But this prints the button with a null phone number which isn't helpful. So then I tried

if([appt.cleanerPhone length]>2)

That was working yesterday but just started crashing my app with this error message pointing to the line above:

2015-04-22 18:59:07.165 [640:158880] -[NSNull length]: unrecognized selector sent to instance 0x37afd690

I also tried

if(appt.cleanerPhone && [appt.cleanerPhone length]>2)

But this leads to the same error.

For reference, these all come from a parsed JSON object->NSDictionary. If there is no cleaner, here's what the NSDictionary shows in NSLog:

    cleaner = "<null>";
    cleanerPhone = "<null>";

So how can I safely and robustly check if a string object of my Appointment class is non-empty? And what's wrong with the two methods above?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
sunny
  • 3,853
  • 5
  • 32
  • 62
  • Also: http://stackoverflow.com/questions/5684157/how-to-detect-if-nsstring-is-null and http://stackoverflow.com/questions/19546920/how-to-check-nsstring-is-null-or-not – Hot Licks Apr 23 '15 at 00:11

1 Answers1

1

You are getting data from JSON or another data interchange format. The conversion makes null into [NSNull null] objects. You need to type check the value before you use it. Try:

if ([appt.cleanerPhone isKindOfClass:[NSString class]] && ([appt.cleanerPhone length] > 2)) {...}
Holly
  • 5,270
  • 1
  • 24
  • 27
  • 1
    To explicitly check for NSNull, compare with `==` to `[NSNull null]`. – Hot Licks Apr 23 '15 at 00:12
  • if ([strpass isEqual:[NSNull null]] || strpass==nil || [strpass isEqualToString:@""] || [strpass isEqualToString:@"(null)"] || strpass.length==0 || [strpass isEqualToString:@""]) { //string is blank } – saurabh rathod Apr 18 '17 at 09:03