How can I consolidate deferred/delayed calls in Objective-C?
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 after开发者_如何学运维Delay:0.5];
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.
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.
精彩评论