Objective c - NSDictionary retaining objects issue

2.2k Views Asked by At

I'll try to explain myself, I have an object Person and a singleton object PeopleManager that has a NSDictionary *_people.
_people is a dictionary that holds Person objects with the personId as key.

When a person is created I add it (self) to the _people dictionary (in the Person init method)

The people dictionary should hold the person object until the person is dealloc, but the problem is that if I alloc the person somewhere in my code and then release it, it won't get dealloc because PeopleManager still holds it in the _people dictionary.

Really the problem is that the _people dictionary retain the person, if it was possible to have an assign dictionary it would be great, but I know it's not possible.

What can I do to solve this?

2

There are 2 best solutions below

0
On BEST ANSWER

The dictionary must retain person because it is using it. If this did not happen, the dictionary could not be guaranteed that it's objects were always still alive.

When you release Person, such that you no longer need it at all and expect it to be dealloc'd, remove it from the dictionary via [NSMutableDictionary -removeObjectForKey:] (and thus decrementing the retain count). This will require use of NSMutableDictionary though because you cannot remove objects from a NSDictionary.

0
On

If you use NSDictionary's mutable counterpart, you would be able to remove the object that's passed out of use with a simple -removeObjectForKey: