objective-cmemory-managementmemory-leaksretain

How to avoid retain cycle when dealing with NSArray(Which retains object by default )?


My situation is that I have two Classes : "Person" and "Group". In every person, it has a NSArray that restores every group it belong to. In every group , it has a NSAraay that restores every person belongs to it.

And one person can belong to many group and one group can have many people belongs to it.

And This is a kind of retain count I think,A person retains a NSArray which retains the Group Which retains a NSArray which retains back to the person.

But I think I do need every person knows which group it belongs to and every group knows the persons belongs to it.

How can I solve this?

I think it the NSArray doesn't retains all it's members that would break the cycle but obviously NSArray must retains them.So please provide some advice.


Solution

  • You can use [NSValue valueWithNonretainedObject:...] to put your objects into an array without retaining them. I'm not sure if this is the best solution, but it will work.