Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSDictionary +dictionaryWithDictionary or -copy?

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.

like image 287
matehat Avatar asked Jun 12 '13 23:06

matehat


2 Answers

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!).

like image 147
Dave DeLong Avatar answered Sep 27 '22 20:09

Dave DeLong


There are a couple things about this question:

Firstly, these two are slightly different:

[NSDictionary dictionaryWithDictionary:otherDictionary];    #1
[otherDictionary copy];                                     #2

#1 returns an autoreleased object (i.e., one with a +0 retain count); #2 returns an object with a +1 retain count, so the caller is responsible for calling release at some point.

(They're also slightly different if otherDictionary is nil: #1 returns an empty dictionary, whereas #2 returns nil.)

Of course, in your question, you actually ask about mutable copies. Note you can do either of these:

[NSMutableDictionary dictionaryWithDictionary:otherDictionary];
[otherDictionary mutableCopy];

The same caveats as above apply to each of these methods.

There's probably not a best way per se, but mutableCopy is the most clear (just remember that you have to release the retained object at some point).

like image 40
mipadi Avatar answered Sep 27 '22 21:09

mipadi