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

2

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.

Indetermination answered 26/9, 2011 at 6:32 Comment(0)
C
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]]) {
  ...
Capsicum answered 26/9, 2011 at 6:45 Comment(0)
A
-2

In a single line

arriveTime ? job.arriveDone = [NSDate dateWithTimeIntervalSince1970:[arriveTime intValue]/1000]; : NSLog(@"Arrive time is not yet scheduled");
Afteryears answered 26/9, 2011 at 6:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.