4

objectForKey:类的方法是否NSMutableDictionary返回对象的副本?

如果我在 aNSMutableArray中存储了 aNSMutableDictionary并且我对objectForKey:使用字典的方法访问的数组进行了一些修改(如添加对象),这些修改是否对存储在字典中的数组有效?

4

2 回答 2

9

不,它不会返回副本。

NSMutableArray *array = [NSMutableArray new];
NSMutableDictionary *dict = [NSMutableDictionary new];

NSLog(@"local instance of array: %p", array);

[dict setObject: array forKey: @"key"];

NSLog(@"returned from dictionary: %p", [dict objectForKey: @"key"]);

输出:

2012-09-16 14:06:36.879 Untitled 3[65591:707] local instance of array: 0x7f98f940a2f0
2012-09-16 14:06:36.884 Untitled 3[65591:707] returned from dictionary: 0x7f98f940a2f0

您将返回相同的指针,这意味着该对象尚未被复制。

于 2012-09-16T13:08:07.503 回答
1

如果你这样做

[collection setObject:obj forKey:key];

您将该对象实例放入集合(字典、数组或集合)中。

如果要在字典中添加对象的副本,则必须这样做

[collection setObject:[obj copy] forKey:key];

无论如何, objectForKey: 方法总是返回您输入的内容,而不是它的副本。

于 2012-09-16T13:12:16.123 回答