On Apr 19, 2013, at 1:01 AM, Oleg Krupnov <[email protected]> wrote:
> I recently encountered an alarming problem that I have never been > aware of, and I'd like to ask about the best practice to handle it. > > Is it true that any object (let's call it Controller) that owns an > NSTimer, scheduled to fire a method (let's call it -timerDidFire) of > the same Controller, creates a circular reference and causes the > Controller to never be released and the timer never stop triggering? > > It looks like scheduling the timer causes the run loop to retain a > reference to the object that implements -timerDidFire, in this case > it's the Controller. Is this true? Then this is a circular reference, > right? > > In this case, if [_timer invalidate]; is called only in Controller's > dealloc, then the timer never stops firing? > > Which is the best way to prevent this problem? Currently I'm thinking > about some kind of -[controller disconnect]; method that I need to > call before [controller release]; in controller's parent object, but > that seems a bit unwieldy solution. > > Any other ideas/considerations? Thanks! What I'd probably do would be to use a GCD timer instead of an NSTimer. That way, you can pass the timer a block instead of a reference to the controller, and as long as you either 1) don't reference self within the block or 2) make a __weak reference to self, and only use that inside the block, your controller won't be retained. Charles _______________________________________________ Cocoa-dev mailing list ([email protected]) 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: https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to [email protected]
