Remember also that retain cycles can occur if your block refers to another object which then retains self
.
I'm not sure that Garbage Collection can help in these retain cycles. If the object retaining the block (which I'll call the server object) outlives self
(the client object), the reference to self
inside the block will not be considered cyclic until the retaining object itself is released. If the server object far outlives its clients, you may have a significant memory leak.
Since there are no clean solutions, I would recommend the following workarounds. Feel free to choose one or more of them to fix your issue.
- Use blocks only for completion, and not for open-ended events. For example, use blocks for methods like
doSomethingAndWhenDoneExecuteThisBlock:
, and not methods like setNotificationHandlerBlock:
. Blocks used for completion have definite ends of lives, and should be released by server objects after they are evaluated. This prevents the retain cycle from living for too long even if it occurs.
- Do that weak-reference dance you described.
- Provide a method to clean up your object before it's released, which "disconnects" the object from server objects that may hold references to it; and call this method before calling release on the object. While this method is perfectly fine if your object only has one client (or is a singleton within some context), but will break down if it has multiple clients. You're basically defeating the retain-counting mechanism here; this is akin to calling
dealloc
instead of release
.
If you are writing a server object, take block arguments only for completion. Do not accept block arguments for callbacks, such as setEventHandlerBlock:
. Instead, fall back to the classic delegate pattern: create a formal protocol, and advertise a setEventDelegate:
method. Do not retain the delegate. If you don't even want to create a formal protocol, accept a selector as a delegate callback.
And lastly, this pattern should ring alarms:
- (void)dealloc {
[myServerObject releaseCallbackBlocksForObject:self];
...
}
If you're trying to unhook blocks that may refer to self
from inside dealloc
, you're already in trouble. dealloc
may never be called due to the retain cycle caused by references in the block, which means that your object is simply going to leak until the server object is deallocated.
self
proxiesthis
just to flip things around. In JavaScript I call mythis
closuresself
, so it feels nice and balanced. :)