16

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.

justin
  • 104,054
  • 14
  • 179
  • 226
Fan Wu
  • 237
  • 1
  • 4
  • 11

2 Answers2

39

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]]) {
  ...
justin
  • 104,054
  • 14
  • 179
  • 226
-2

In a single line

arriveTime ? job.arriveDone = [NSDate dateWithTimeIntervalSince1970:[arriveTime intValue]/1000]; : NSLog(@"Arrive time is not yet scheduled");
Praveen-K
  • 3,401
  • 1
  • 23
  • 31