Search code examples
iphoneiosnsdictionarynull

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


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"];

Solution

  • It wants an actual object... use NSNull

    [NSNull null];