正如我在标题中提到的,我的dispatch_async正在发射10次。我使用它来使GUI更具响应性。但是当它发射10次时,需要很长时间才能完成它必须做的所有事情。这是代码:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
[self calculateAllThatShizzle];
});
calculateAllThatShizzle方法只有大约150行计算(包括很多循环)。
我确实尝试了以下内容:
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
[self calculateAllThatShizzle];
});
但是它似乎只在整个生命周期中使用过一次,我需要在每次显示页面时触发它。
所以问题是:如何强制dispatch_async只触发一次?
任何帮助将不胜感激,谢谢
修改
这些dispatch_async和dispatch_once位于checkAndCalculateIfNecessary方法中。这个方法是从PageControl调用的,如:
- (void)scrollViewDidScroll:(UIScrollView *)sender {
// We don't want a "feedback loop" between the UIPageControl and the scroll delegate in
// which a scroll event generated from the user hitting the page control triggers updates from
// the delegate method. We use a boolean to disable the delegate logic when the page control is used.
if (pageControlUsed) {
// do nothing - the scroll was initiated from the page control, not the user dragging
return;
}
// Switch the indicator when more than 50% of the previous/next page is visible
CGFloat pageWidth = scrollView.frame.size.width;
int page = floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
pageControl.currentPage = page;
DetailViewController *controller = [viewControllers objectAtIndex:page];
[controller saveTheValues];
// load the visible page and the page on either side of it (to avoid flashes when the user starts scrolling)
[self loadScrollViewWithPage:page - 1];
[self loadScrollViewWithPage:page];
[self loadScrollViewWithPage:page + 1];
if ((page + 1) == kNumberOfPages) {
[controller checkAndCalculateIfNeccessary];
}
}
答案 0 :(得分:2)
我认为这种情况正在发生,因为scrollViewDidScroll:
方法在用户滚动内容时被多次调用,尝试在– scrollViewDidEndDecelerating:
中进行计算和/或设置一个bool值来控制计算是否应该触发。