0

I'm new to objective c and I've got an interesting situation where I need two different NSDictionary objects that point to the same values. In that situation should I use strong or weak in the property declaration? Or should I do strong in one and weak in the other?

In Game.m

@property (strong/weak, nonatomic) NSDictionary* answers1;

In User.m

@property(strong/weak, nonatomic) NSDictionary* answers2;

In both cases the key will be an integer, but the value will be an answer object of my own making. Both answers1 and answers2 will need to exists for roughly the same amount of time. When it comes time to get rid of one it'll be okay to get rid of the other.

Kara
  • 6,115
  • 16
  • 50
  • 57
CamHart
  • 3,825
  • 7
  • 33
  • 69

2 Answers2

3

Both should probably be strong. Each class should do its own memory management without having to worry about what other classes are doing. Therefore, each should keep its own strong reference.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • Actually, `copy` would be even better for a dictionary. – Léo Natan Nov 22 '13 at 23:20
  • 1
    `copy` would be a good choice if there is any chance you might assign a mutable dictionary and you want to ensure the property's values aren't changed due to changes in the mutable dictionary. – rmaddy Nov 22 '13 at 23:31
0

In this case, the best would actually be copy. This way, in addition to retaining the dictionary, you will create an immutable copy of the one passed to you, ensuring the dictionary does not get modified from an outside influence (for example, passing a mutable dictionary which can later mutate).

Léo Natan
  • 56,823
  • 9
  • 150
  • 195
  • It depends on the situation. If both properties should point to the same dictionary instance, copy might not be what you want. Any way, the whole setup is questionable. – Nikolai Ruhe Nov 22 '13 at 23:22
  • The problem you propose has a solution with copy, but it is a peculiar problem. In most cases, copying is preferable outside of some side cases, like the one you propose. – Léo Natan Nov 22 '13 at 23:25