I use performSelector:withObject:afterDelay:
to delay a layout operation so that it's not done multiple times. Normally, I do something like this (example only):
- (void) setViewNeedsLayout{
if (!_viewsNeedLayout){
_viewsNeedLayout = YES;
[self performSelector:@selector(layoutViews) withObject:nil afterDelay:0];
}
}
- (void) layoutViews{
_viewsNeedLayout = NO;
//layout views
}
It's pretty simple, efficient and effectively delays the layout operation until the end of the current run loop, but it does require that I keep track of the ivar: _viewsNeedLayout
.
However, I'm wondering about the performance of cancelPreviousPerformRequestsWithTarget:selector:object:
. Instead of using an iVar to keep track of whether I've kicked off the delayed selector, I'm wondering if it might be better to do something like this:
- (void) setViewNeedsLayout{
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(layoutViews) object:nil];
[self performSelector:@selector(layoutViews) withObject:nil afterDelay:0];
}
Now, the issue is how performant is cancelPreviousPerformRequestsWithTarget
? In some cases, the respective setViewNeedsLayout
method (or equivalent) could get called possibly hundreds of times... as an extreme example. But it is an easier way to deal with the delayed/queued method call so I'd prefer to use it if it's not going to have a significant impact on performance.