1

According to Apple's documentation, if I add an object to an NSMutableDictionary via the setObject:forKey: method, the dictionary will keep a strong reference to it.

But what about the setValue:forKey: method? The documentation doesn't say anything about the kind of reference to the object added via this method. Is it the same as the other one? Does the dictionary keep a strong reference to the object added via this method as well?

notadam
  • 2,754
  • 2
  • 19
  • 35

2 Answers2

4

NSMutableDictionary (and NSMutableArray) keeps strong references to any object added to it, no matter how it is added.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
3

NSMutableArray and NSArray keep strong references to objects they contain. These objects are either added using the literal constructor @[myObject, myObject2, ...], the initializers of NSArray, or the add/insert methods of NSMutableArray.

If you're looking for key/value storage like a map, you want to use NSDictionary/NSMutableDictionary instead. The setValue:forKey: method you're talking about is for key-value coding compliance, which is different.

Additionally, NSDictionary and NSMutableDictionary keep strong references to value objects, and keep copy references to keys (which must comply to the NSCopying protocol).

wjl
  • 7,143
  • 1
  • 30
  • 49
  • 1
    I meant `NSMutableDictionary` in the question, sorry. I wrote `NSMutableArray` by mistake but I corrected it. But thanks anyway :) – notadam Sep 11 '14 at 16:58