NSDictionary +dictionaryWithDictionary or -copy?

matehat picture matehat · Jun 13, 2013 · Viewed 12.2k times · Source

Which is considered the better way to derive a new dictionary from an original one:

[NSDictionary dictionaryWithDictionary:otherDictionary];

or

[otherDictionary copy];

?

From time to time we need to make a mutable dictionary out of an immutable one, and so this question keeps coming in. Maybe there is none, but I'm curious to see if in some use cases one is better than the other.

EDIT: I do know the above methods cannot be used to derive a mutable dictionary. I just wanted to ask the question in a general way, and then explain how I face this question from day to day. I should've been more clear about that.

Answer

Dave DeLong picture Dave DeLong · Jun 13, 2013

Actually, they are different, but not for the reason you expect. I'm going to assume you're using ARC (and if you're not, why not?), so the auto-releasedness of the returned object doesn't matter.

Here's how they differ: consider what happens if otherDictionary is nil.

Well, if you use:

[otherDictionary copy]; // or -mutableCopy

You'll get back nil, because you have a nil receiver.

On the other hand, if you use:

[NS(Mutable)Dictionary dictionaryWithDictionary:otherDictionary];

You will get back an NS(Mutable)Dictionary, regardless of whether otherDictionary is nil or not.

This is nice in the situation where you need to create a copy of a dictionary and want an NSDictionary instance afterwards, but you don't want to test for nil (yay for reducing cyclomatic complexity!).