iOS: Why can't I set nil to NSDictionary value?

applefreak picture applefreak · Aug 17, 2012 · Viewed 38.3k times · Source

This might be very basic question but I was wondering why can't I assign nil as NSDictionary value? I have following statement many places in my code. If [q objectForKey:@"text"] is nil then App is crashing.

NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithCapacity:2];
[dict setObject:[q objectForKey:@"text"] forKey:@"text"];

I have to check everywhere for the nil before assigning it to dictionary. Is this the only correct way of doing? Am I missing something obvious?

if([q objectForKey:@"text"] != nil)
    [dict setObject:[q objectForKey:@"text"] forKey:@"text"];
else
    [dict setObject:@"" forKey:@"text"];

Answer

tybro0103 picture tybro0103 · Aug 17, 2012

It wants an actual object... use NSNull

[NSNull null];