12

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.

4

4 回答 4

34

实际上,它们不同的,但不是出于您期望的原因。我将假设您正在使用 ARC(如果不是,为什么不呢?),因此返回对象的自动释放无关紧要。

以下是它们的不同之处:考虑如果otherDictionaryis会发生什么nil

好吧,如果你使用:

[otherDictionary copy]; // or -mutableCopy

你会回来nil的,因为你有一个nil接收器。

另一方面,如果您使用:

[NS(Mutable)Dictionary dictionaryWithDictionary:otherDictionary];

得到一个NS(Mutable)Dictionary,无论otherDictionary是否nil

这在您需要创建字典副本并在之后想要一个NSDictionary实例的情况下很好,但您不想测试nil(是的,可以降低圈复杂度!)。

于 2013-06-13T00:29:48.267 回答
7

关于这个问题有几件事:

首先,这两者略有不同:

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

#1 返回一个自动释放的对象(即,保留计数为 +0 的对象);#2 返回一个具有 +1 保留计数的对象,因此调用者负责release在某个时候调用。

otherDictionary(如果is ,它们也略有不同nil:#1 返回一个空字典,而 #2 返回nil。)

当然,在您的问题中,您实际上询问的是可变副本。请注意,您可以执行以下任一操作:

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

与上述相同的警告适用于这些方法中的每一种。

本身可能没有最好mutableCopy的方法,但最清楚(请记住,您必须在某个时候释放保留的对象)。

于 2013-06-12T23:30:01.537 回答
3

它们在语义上是等价的。使用哪一个完全是一个选择问题。我赞成-copy,只是因为它更短,并且使发生的事情更清楚。

如果您需要一个可变副本(如您的文本所示),您发布的行将不起作用。你需要:

[NSMutableDictionary dictionaryWithDictionary:otherDictionary];

或者,等效地:

[otherDictionary mutableCopy];

在内存管理方面,-copyand -mutableCopy,返回一个保留计数为 +1 的对象,这意味着您需要在完成它们后释放它们。-dictionaryWithDictionary:返回一个自动释放的对象,所以当你完成它时不需要释放它,如果你想保留它就需要保留它。在过去(ARC 之前)的日子里,这种区别意味着您使用哪种方法可能取决于您的内存管理需求(当然,在额外的保留或释放之后,它们仍然可以互换)。当然,如果您使用的是 ARC,那么这种区别对您来说并不重要。

于 2013-06-12T23:23:44.047 回答
0

Cocoa 认可的方法是发送一个 mutableCopy 方法,该方法返回一个可变副本:

NSMutableDictionary *mutableOtherDictionaryCopy = [otherDictionary mutableCopy]
于 2013-06-12T23:23:31.090 回答