Re: Circular references caused by scheduled NSTimers?
Re: Circular references caused by scheduled NSTimers?
- Subject: Re: Circular references caused by scheduled NSTimers?
- From: Oleg Krupnov <email@hidden>
- Date: Fri, 19 Apr 2013 19:01:03 +0300
> 2) make a __weak reference to self, and only use that inside the block, your controller won't be retained.
That's another alarming problem that I have become aware of in context
of my question. It turns out that if you use blocks instead of
delegates inaccurately, you can end up
creating a strong reference (e.g. by mentioning self in the block) and
a circular reference even without being aware of it. I am now
seriously thinking that blocks can be evil for replacing delegates
(which by convention are always assign properties, i.e. weak
references). Am I right?
On Fri, Apr 19, 2013 at 10:10 AM, Charles Srstka
<email@hidden> wrote:
> On Apr 19, 2013, at 1:01 AM, Oleg Krupnov <email@hidden> 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@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