Le 12 août 09 à 17:55, Christopher Kane a écrit :

On Aug 11, 2009, at 10:28 AM, Fritz Anderson wrote:

iPhone OS 3.0

Can an NSTimer be rescheduled after firing, and after another trip through the run loop?

I'd like to "reschedule" a NON-repeating timer in my own code. I assume that in the simple case it would be something like:

- (void) handleTimer: (NSTimer *) aTimer
{
        //      ... do things ...
        [aTimer setFireDate: someTimeInTheFuture];
[[NSRunLoop currentRunLoop] addTimer: aTimer forMode: NSDefaultRunLoopMode];
}

I'm pretty sure that this is legal — am I right?

No, as you suspected farther down in your message. NSTimers which are not repeating are one-shot -- they cannot be rescheduled. Create a new NSTimer, when you next need it, and add it to the run loop. [And also self.myTimerIvar = nil; in your timer handler as you thought.]


An alternative would be to create a repeating timer with long interval and reschedule it as necessary (as explained in the CFRunLoopTimerSetNextFireDate() reference)

Discussion
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.


_______________________________________________

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