On Aug 3, 2012, at 14:37 , Trygve Inda <cocoa...@xericdesign.com> wrote:

> I think B is the concern since if I
> change the code to:
> 
> if ([updateTimer isValid])
> [updateTimer invalidate];
> 
> Then it will be invalidated in case B (because the code has not fallen back
> to the run loop to invalidate it on its own). Not sure if I should be
> invalidating it after it has fired in this case...before the system does

I think you're over-thinking the problem here. There's no reason to think that 
'invalidate' is fragile. If the timer's still scheduled to fire, 'invalidate' 
will prevent from "ever firing", according to the class documentation. 
Otherwise it's harmless.

You don't care (and the documentation tells you not to care) when it's actually 
removed from the run loop. All you care about is that it won't fire.

> -(void)setUpdateTimer:(NSTimer *)inTimer
> {
>    if (updateTimer)
> 
>        [updateTimer invalidate];
>        [updateTimer release];
>        updateTimer = nil;
>    }
> 
>    updateTimer = [inTimer retain];
> }

You don't even need to be this careful. This shorter implementation is 
guaranteed to be just as safe:

> -(void)setUpdateTimer:(NSTimer *)inTimer
> {
>    [updateTimer invalidate];
>    [updateTimer release];
> 
>    updateTimer = [inTimer retain];
> }

It's also preferable to release the expired timer earlier, in the case where a 
new timer isn't started right away:

> -(void)wantsUpdate:(NSTimer *)inTimer
> {
>    [updateTimer release];
>    updateTimer = nil;
> 
>    // do stuff
> 
>    // conditionally do
>    [self setUpdateTimer:[NSTimer scheduledTimerWithTimeInterval:kSomeValue
>    target:self selector:@selector(wantsUpdate:) userInfo:nil repeats:NO]];
> }

> How best to handle all three cases elegantly?

Personally, I'd do it the neater but slightly redundant way:

> -(void)awakeFromNib
> {
>    [self startUpdateTimer];
> }
> 
> 
> -(void)wantsUpdate:(NSTimer *)inTimer
> {
>    [self stopUpdateTimer];
> 
>    // do stuff
> 
>    // conditionally do
>    [self startUpdateTimer];
> }
> 
> -(void)stopUpdateTimer
> {
>    [updateTimer invalidate];
>    [updateTimer release];
>    updateTimer = nil;
> }

> 
> -(void)startUpdateTimer
> {
>    [self stopUpdateTimer];
>    updateTimer = [[NSTimer scheduledTimerWithTimeInterval:kSomeValue
>        target:self selector:@selector(wantsUpdate:) userInfo:nil repeats:NO] 
> retain];
> }


_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

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 arch...@mail-archive.com

Reply via email to