Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 889
Fan Wu Avatar asked Sep 26 '11 06:09

Fan Wu


People also ask

How do you check if an object is NSNull?

We can use NSNull to represent nil objects in collections, and we typically see NSNull when we convert JSON to Objective-C objects and the JSON contained null values. Our preferred way to check if something is NSNull is [[NSNull null] isEqual:something] .

How do I check if a string is NULL in Objective-C?

So a good test might be: if (title == (id)[NSNull null] || title. length == 0 ) title = @"Something"; Save this answer.

What does nil mean in C?

Objective-C builds on C's representation of nothing by adding nil . nil is an object pointer to nothing. Although semantically distinct from NULL , they are technically equivalent.

What is NSNull in Swift?

A singleton object used to represent null values in collection objects that don't allow nil values.


1 Answers

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]]) {
  ...
like image 183
justin Avatar answered Oct 21 '22 03:10

justin