Swati
Swati

Reputation: 1443

Adding key values to nsdictionary misses keys

I have been adding key value pairs to nsdictionary like this

NSDictionary *dict = @{key1:value1, key2:value2};

if value1 is not found, the app crashes. So, I implemented the other way of doing it

NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:value1,key1,value2,key2,nil];

In this case, if value1 is not found, dict does not go further and does not have key2. What is the solution to this?

Upvotes: 0

Views: 920

Answers (2)

Swati
Swati

Reputation: 1443

I have found the solution

 NSMutableDictionary *dict2 = [NSMutableDictionary dictionary];
   [dict2 setValue:value1 forKey:key1];
   [dict2 setValue:value2 forKey:key2];
   [dict2 setValue:value3 forKey:key3];

    NSLog(@"dict2 - %@",dict2);

Works like a charm !!!

Upvotes: -1

Nef10
Nef10

Reputation: 946

NSDictionary (as well as NSArray) cannot store nil, because they expect an object.

A solution would be to use NSNull or to not store the value at all. In the later case the objectForKey: method will return nil if it does not find the value for the given key, which might be want you want.

In the second code example the problem that it is not going further is that this method expects an nil-terminated list so it just stops at the first nil as it thinks this is the end.

You can use setValue:forKey:, this will just remove the value for the key if the value is nil. See here. But therefore it need to be a mutable array and you have to go through all values one by one.

Another solution would be to guard each value with a check, e.g. as shown here.

Upvotes: 2

Related Questions