Re: Could somebody please fix NSTimer?
Re: Could somebody please fix NSTimer?
- Subject: Re: Could somebody please fix NSTimer?
- From: Gwynne Raskind <email@hidden>
- Date: Sat, 12 Jan 2013 14:39:57 -0500
On Jan 12, 2013, at 2:05 PM, Kyle Sluder <email@hidden> wrote:
> On Jan 12, 2013, at 10:49 AM, Gordon Apple <email@hidden> wrote:
>
>> When compiled under ARC, NSTimer should have a weak, not strong, reference
>> to its target. When the timer starts to fire, check the reference for nil
>> and invalidate itself. Come on guys, how hard is that? You wouldnÂąt even
>> have to keep a reference to it, unless you want to invalidate it before the
>> target deallocates.
>
> You should already be invalidating it before the target deallocates…
Not to mention, just use a dispatch timer:
// THIS ASSUMES ARC
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
dispatch_source_set_timer(timer, dispatch_time(DISPATCH_TIME_NOW, myFiringInterval * NSEC_PER_SEC), myFiringInterval * NSEC_PER_SEC, 10000/*leeway*/);
__typeof__(self) __weak w_self = self;
dispatch_source_set_event_handler(timer, ^ {
__typeof__(self) __strong s_self = w_self;
if (!s_self) {
dispatch_cancel(timer);
return;
}
/* do your stuff here, make sure you use s_self instead of self */
});
dispatch_source_set_cancel_handler(timer, ^ {
dispatch_source_set_event_handler(timer, NULL);
dispatch_source_set_cancel_handler(timer, NULL); // kill the cycle
});
dispatch_resume(timer);
Boom, self-destructing timer. Warning: Written in Mail and totally untested. Also, don't do this, just manage your timers properly.
-- Gwynne Raskind
_______________________________________________
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