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

最佳答案

我认为是因为用户滚动内容时多次调用scrollViewDidScroll:方法,尝试在– scrollViewDidEndDecelerating:中进行计算和/或设置布尔值来控制是否触发计算。

10-08 08:59