compare string to null

Discussion in 'iPhone/iPad Programming' started by tranvutuan, Feb 9, 2012.

  1. macrumors member

    Joined:
    Dec 19, 2011
    #1
    After parsing and get values for each elements from XML, one of the field is null like below

    Code:
    myXML.h
    @property (strong, nonatomic) NSString *address;
    @property (strong, nonatomic) NSString *phone;
    Below is my xml structure
    Code:
    <myXML>
      <address> A Street </address>
      <phone>  (null)      </phone>
    </myXML>
    I am doing a checking :
    Code:
    if ( ![myMXL.phone isEqualToString:@"null"] ) {
          NSLog(@"phone is not null");
    else
          NSLog(@"phone is null");
    After running the codes, the debugger gives me
    Code:
    phone is not null
    It seems isEqualToString is not working.I also try !(myXML.phone == NULL) and !([myXML.phone isEqual:NULL]), but still get same problem
    Does anyone have an idea about this.. pls advice me. Thanks
     
  2. thread starter macrumors member

    Joined:
    Dec 19, 2011
    #2
    I've just found the way how to solve this issue. Because phone is NNString so we can count the length of it. Therefore, instead of comparing to null, I did
    Code:
    if (!([phone length] == 0 ))
       // do sth here
    But I am still looking for other solutions, so please answer if you have another solution. Thanks
     
  3. macrumors 6502

    dantastic

    Joined:
    Jan 21, 2011
    #3
    (null) is not a string, it's nothing. you can't compare it to the string "null"

    if you want to check for null do
    Code:
    if (myMXL.phone) {
       NSLog(@"phone has a value: %@", myMXL.phone);
    } else {
       NSLog(@"this will print (null): %@", myMXL.phone);
    }
    
     
  4. thread starter macrumors member

    Joined:
    Dec 19, 2011
    #4
    I have just gave it a try but it does not work... What I got from the console is
    Code:
    phone has a value :(null)
    I dont know why because we already know from OP, my phone is null
     
  5. macrumors 6502

    dantastic

    Joined:
    Jan 21, 2011
    #5
    odd..
    Or do you actually have a string with "(null)" in it?
    If you add

    Code:
    if (myMXL.phone) {
       NSLog(@"phone has a value: >%@< of Kind: %@, length: %i", myMXL.phone, [myMXL.phone class], [myMXL.phone length]);
    } else {
       NSLog(@"this will print (null): %@", myMXL.phone);
    }
    
     

Share This Page