Reputation: 753
I have this app where I am populating an NSDictionary and then doing computations on the dictionary.
tmp = nil;
tmp = [singleEvent objectForKey:@"start_date"];
if(tmp == nil)
{
startDate = [dateFormatter dateFromString:@"1800/1/1 12:00:00"];
}
else
{
startDate = [dateFormatter dateFromString:tmp];
}
tmp is an NSString object, and singleEvent is an NSDictionary. Both are declared elsewhere. I did not include that part of the code for simplicity.
The key "start_date" of the dictionary will sometimes contain a date in string format, and sometimes it will be null.
I have handled the condition where it will be null, but the code never hits that line. I found out by debugging that even when tmp is null the executions goes to else part.
In debug mode I get this when watching tmp:
tmp = (NSNull *)
But still else block is hit. So I am always getting a null pointer exception.
Upvotes: 0
Views: 150
Reputation: 11016
The key "start_date" of the dictionary will sometimes contain a date in string format, and sometimes it will be null.
There's three cases:
start_date
is not in your dictionary : the return value of objectForKey:
will be nil
(first condition is true);start_date
is in your dictionary and the value associated is [NSNull null]
(of type (NSNull *)
: the return value of objectForKey:
will be [NSNull null]
(second condition is true);start_date
is in your dictionary and the value associated is something else : the return value of objectForKey:
will be the stored object (second condition is true);But #2 and #3 really are the same: NSNull
is an object like every other.
Do not confuse a null pointer (nil
) and the Null object ([NSNull null]
). To test the first, you have to do:
if (!tmp)
// or
if (tmp == nil)
and for the second:
if (tmp == [NSNull null])
Upvotes: 2
Reputation: 21464
NSNull
is different to nil
. NSNull
(or, more explicitly, [NSNull null]
) is a singleton used to represent the concept of "nil" that can be used in the Foundation collection classes. Because it's a singleton, you don't have to use -isEqual:
, you can compare it directly.
To check for NSNull
, you can do this:
if (tmp == [NSNull null])
Upvotes: 9
Reputation: 3239
How about making it a bit smaller like that ? also I think your problem was you're using objectForKey not valueForKey, valueForKey will return Nil.
startDate = [dateFormatter dateFromString:@"1800/1/1 12:00:00"];
if([singleEvent valueForKey:@"start_date"])
startDate = [dateFormatter dateFromString:[singleEvent valueForKey:@"start_date"]];
NSLog(@"%@", startDate);
Upvotes: -1
Reputation: 3549
NSNull is a different thing than nil. Perhaps this will work:
if ( [[NSNull null] isEqual:tmp] ) {
Upvotes: 1