I have a library that potentially creates and invalidates/destroys a lot of NSTimers. Basically, users request operations to be completed and they pass an optional timeout. If the operation completes in the appropriate time, the timer is invalidated. Otherwise the timer fires, and the operation is cancelled. Operations are queued, and only one operation is executed at a time.

So I was wondering if it would be better to create a single repeating NSTimer, and simply change its fireDate. The documentation for CFRunLoopTimerSetNextFireDate seems to indicate as much:

Resetting a timer’s next firing time is a relatively expensive operation and should not be done if it can be avoided; letting timers autorepeat is more efficient. In some cases, however, manually- adjusted, repeating timers are useful. For example, if you have an action that will be performed multiple times in the future, but at irregular time intervals, it would be very expensive to create, add to run loop modes, and then destroy a timer for each firing event. Instead, you can create a repeating timer with an initial firing time in the distant future (or the initial firing time) and a very large repeat interval—on the order of decades or more—and add it to all the necessary run loop modes. Then, when you know when the timer should fire next, you reset the firing time with CFRunLoopTimerSetNextFireDate, perhaps from the timer’s own callback function. This technique effectively produces a reusable, asynchronous timer.

However I'm not sure how safe it is to use the setFireDate method of NSTimer. Consider the following code:

NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.2
                                                  target:self
selector:@selector(timeout:)
                                                userInfo:nil
                                                 repeats:NO];

[NSThread sleepForTimeInterval:2.0];

// This line will properly prevent the timer from firing        
//[timer invalidate];

// This line will NOT
[timer setFireDate:[NSDate distantFuture]];

Why is this exactly?_______________________________________________

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:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to