Avoiding mutual retain cycles
Avoiding mutual retain cycles
- Subject: Avoiding mutual retain cycles
- From: Markus Spoettl <email@hidden>
- Date: Mon, 21 Jul 2008 11:50:12 -0700
Hi List,
in the course of debugging a -dealloc in a data structure that is
part of an NSDocument app, I've discovered that my document and all
it's data never gets deallocated. After some extensive digging I
nailed the problem down to mutual retain cycles (not sure this is the
right term). I actually had a number of those, it always followed this
scheme:
An object A was retained by an object B which was owned by A. A
releases B in its -dealloc, B releases A in its -dealloc. Since
neither retain count would ever go to zero, neither dealloc would ever
be called and everything would just stay there forever.
By changing the reference from B to A to a weak reference which
doesn't retain and release A, the problem goes away. However,
generally speaking this is dangerous road to go (and against memory
management guidelines) because now it's no longer guaranteed that A
still exists if B is using it. Sure, there could be measures
implemented that help with that (like A notifying B that it's going
away) but that would mean a lot of additional housekeeping.
Defining who owns who (owners get a strong reference to owned) also
helps, because it's then guaranteed that A will be there for as long
as B exists, thus a strong reference is not needed. But there are
still cases where it is unknown which of the objects is going to be
released first (because it's hidden in the inner workings of AppKit
for example).
I'm wondering if there is a general rule or mechanism that suggests
what to do in such a case. For instance, how are delegates implemented
in AppKit, are they retained? If so, when are they released. It can't
be in -dealloc, otherwise everything would lock itself out of
deallocation?
Thoughts?
Markus
--
__________________________________________
Markus Spoettl
Attachment:
smime.p7s
Description: S/MIME cryptographic signature
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden