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"];
It wants an actual object... use NSNull
You can set nil object in this way:
Have you noticed it?
You can set a nil value using
setValue:forKey
but it removes the key.If you want to be able to set a key to
nil
you could usesetValue:forKey:
which will remove the key if you set it tonil
(quote from documentation below). Note the Value instead of Object.When you later try and get the object using
objectForKey:
for the key that you removed by setting it tonil
you will getnil
back (quote from documentation below).Note: The key will not actually be present in the dictionary so it won't be obtained using
allKeys
; or be enumerated over.When using this method:
Parameters (according to Apple doc's):
anObject:
aKey
My friend using nil as marker is a sign of bad programming . nil is reserved for some diffrent purpose .
//by default for all the keys the value is nil and you are trying to override this behavior. going against the language rules will always get you in trouble .
to check just use