anon
anon

Reputation:

How can i use [NSMutableDictionary dictionaryWithDictionary] if the dictionary is empty?

I get some data from the server and save it to NSDictionary then I want to initialise NSMutableDictionary with that NSDictionary.

NSDictionary  * const received = [self serverData];
NSMutableDictionary * const results = [NSMutableDictionary dictionaryWithDictionary:received];

And If I get empty JSON from the server and consequently my NSDictionary will be empty how can I use dictionaryWithDictionary for an empty one? I use this

NSDictionary * const received = [self serverData];
NSMutableDictionary * const results;
if (![received count]) {
    results = [NSMutableDictionary dictionary];
}
else
{
    results = [NSMutableDictionary dictionaryWithDictionary:received];
}

But it seems a code smell. May be there are more elegant solutions?

Upvotes: 2

Views: 3941

Answers (3)

James P
James P

Reputation: 4836

You were fine in the first place.

NSDictionary* received = [self serverData];
NSMutableDictionary* results = [NSMutableDictionary dictionaryWithDictionary:received];

Will do what you want. Even if received is nil or empty, results will just be an empty NSMutableDictionary.

Upvotes: 5

phoganuci
phoganuci

Reputation: 5064

I would make a category on NSDictionary that provides for such a safe setting.

+ (NSMutableDictionary *)safeDictionaryWithDictionary:(NSDictionary *)dictionary
{
    return [NSMutableDictionary dictionaryWithDictionary:(dictionary ? dictionary : @{});
}

Upvotes: 1

Anoop Vaidya
Anoop Vaidya

Reputation: 46543

You cant create an item in dictionary with "no key". As key must be a non-nil string.

If no items are there then no object and no key are set, this leads to setObject:nil forKey:nil

Upvotes: 0

Related Questions