views:

47

answers:

2

I'd like to ensure that certain maintenance tasks are executed "eventually". For example, after I detect that some resources might no longer be used in a cache, I might call:

[self performSelector:@selector(cleanupCache) withObject:nil afterDelay:0.5];

However, there might be numerous places where I detect this, and I don't want to be calling cleanupCache continuously. I'd like to consolidate multiple calls to cleanupCache so that we only periodically get ONE call to cleanupCache.

Here's what I've come up with do to this-- is this the best way?

[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(cleanupCache) object:nil]; [self performSelector:@selector(cleanupCache) withObject:nil afterDelay:0.5];

A: 

Rather than canceling the pending request, how about just keeping track? Set a flag when you schedule the request, and clear it when the cleanup runs.

David Gelhar
I guess what I'm wondering is: Is there a way to get NSObject to do that for me? It clearly is already keeping track of what delayed selectors are queued.
thrusty
A: 

There's no real built-in support for what you want. If this is common in your program, I would create a trampoline class that keeps track of whether it's already scheduled to send a message to a given object. It shouldn't take more than 20 or so lines of code.

Chuck