On Sep 23, 2008, at 6:20 PM, Dan Birns wrote:

My application needs to set a timer that causes a function to be called at a time in the future. This is non-repeating, and sometimes has be immediate.

NSTimer is a good choice. Another thing to consider, if it meets your needs, is -performSelector:withObject:afterDelay:.


I need it to be as efficient as possible, because it's called frequently. [...] This is working fine, but our performance is poor. It's not so poor that it's obviously broken, but I'm looking for ways to improve it.

How frequent is "frequent"? I ask because it seems highly improbable that allocating an NSTimer object would impact performance for a timer of reasonable frequency. A rate high enough that object allocation constitutes a significant fraction of the performance probably exceeds what an NSTimer is useful for. NSTimer isn't appropriate for real- time processing.

Also, in what way is your performance poor? Have you measured the nature of the problem using Shark or the like?


I've been try to alloc one NSTimer that I reuse, and I've had no success doing so.

I've tried

        timer = [NSTimer alloc];
[timer initWithFireDate:[NSDate date] interval:t target:self selector:@selector(mainLoopTimer:) userInfo:halTimer repeats:NO];

Never separate the alloc from the init expressions like this. The init method is entitled to return a different object than that which was returned from alloc, in which case your "timer" variable is left holding the wrong thing.



[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];

This has failed. Investigating, I called [timer isValid] and it returns false. I've tried altering the args in various ways without success. I've also had various problems retain'ing this timer. When I add [timer retain];, it crashes having exhausted the stack, where it's calling retain over and over.

All of the above symptoms may be due to the separate of alloc from init.


One technique you can try to get a single timer that you can reuse is to create one with a ridiculously large repeat interval. Then, when you have a real time when you need it to fire, use the -setFireDate: method to give it a new fire date. After it fires, it will reschedule itself using the very large repeat interval, which will be way off into the future. In other words, it will be essentially dormant until you again set a new fire date.

Cheers,
Ken

_______________________________________________

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 [EMAIL PROTECTED]

Reply via email to