Search code examples
iphonejsonnsmutabledictionarynsnull

How to make a if statement with NSNull in objective-c


I am develop a iPhone application, in which i need to use JSON to receive data from server. In the iPhone side, I convert the data into NSMutableDictionary.

However, there is a date type data are null.

I use the following sentence to read the date.

NSString *arriveTime = [taskDic objectForKey:@"arriveTime"];
NSLog(@"%@", arriveTime);

if (arriveTime) {
    job.arriveDone = [NSDate dateWithTimeIntervalSince1970:[arriveTime intValue]/1000];
}

When the arriveTime is null, how can i make the if statement. I have tried [arriveTime length] != 0, but i doesn't work, because the arriveTime is a NSNull and doesn't have this method.


Solution

  • the NSNull instance is a singleton. you can use a simple pointer comparison to accomplish this:

    if (arriveTime == nil) { NSLog(@"it's nil"); }
    else if (arriveTime == (id)[NSNull null]) { // << the magic bit!
      NSLog(@"it's NSNull");
    }
    else { NSLog(@"it's %@", arriveTime); }
    

    alternatively, you could use isKindOfClass: if you find that clearer:

    if (arriveTime == nil) { NSLog(@"it's nil"); }
    else if ([arriveTime isKindOfClass:[NSNull class]]) {
      ...