正如我在标题中提到的,我的 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];
}
}