【发布时间】:2012-04-11 08:28:30
【问题描述】:
正如我在标题中提到的,我的 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];
}
}
【问题讨论】:
-
dispatch_async 方法在哪里被调用?
-
@danielbeard 在 PageControl 滚动到该页面时调用的方法中
-
- (void)scrollViewDidScroll:(UIScrollView *)scrollView ?
-
@danielbeard 是的。我还编辑了问题
标签: iphone objective-c ios dispatch