Activity 带循环的指标

Activity Indicator with loop

我正在使用一个应用程序,它有一个循环可以完成很多工作。循环生成一串数字,然后将它们放入一个UITableView中。我想在工作进行时显示 UIActivityIndicatorView。我在屏幕上添加了 activity 指示器并将其居中。起初,我根本没有让 activity 指示器显示。我意识到这是因为 activity 指示器与循环在同一线程上 运行,并且当循环处于 运行 时指示器永远不会更新。我研究了如何创建后台线程,然后想到了这个。

    self.progressIndicator.startAnimating()

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), { () -> Void in
        for var instance = 0; instance < numberCount!; instance++ {
            //Lots of work done in here.  Items are added to a
            //collection that is used to populate the table view.
            //Takes around 10 seconds to execute.
        }
        NSNotificationCenter.defaultCenter().postNotificationName("FinishedNumbers", object: nil)
    });

activity指标在主线程运行,后台处理循环运行。我创建了一个通知程序,它调用一个函数来调用 reloadList 并在数字列表完成后停止 activity 指示器。

func doneWithCreateNumbers(notification: NSNotification) {
    self.numberList.reloadData()
    self.progressIndicator.stopAnimating()
}

虽然这确实有效,但效果不佳。有几个问题。

尽管循环处理在 10 秒内完成,但填充列表和 activity 指标停止旋转需要更长的时间。我在 doneWithCreateNumbers 函数中放置了一个断点并检查了数字集合的计数,它确实包含正确数量的项目。在重新加载列表并停止 activity 指标的代码执行后,填充列表和 activity 指标停止 运行 需要 30 到 40 秒。

列表最终会填充并且指示器消失,但我在调试中收到此错误消息 window:

This application is modifying the autolayout engine from a background thread, which can lead to engine corruption and weird crashes. This will cause an exception in a future release.

我尝试过以多种方式重新安排所有这些,但没有比我现在所做的更有效的了。我重新安排的方法之一是将 reloadData 和 stopAnimating 放在循环之后。它并没有更好地工作,我仍然得到上面列出的错误。

我在这里遗漏了一些东西,但不确定是什么。有什么想法吗?

试试这个:

let activityIndicator = UIActivityIndicatorView.init(activityIndicatorStyle:UIActivityIndicatorViewStyle.WhiteLarge)
self.view.addSubview(activityIndicator)

// Switch To Background Thread
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) { () -> Void in

    // Animate Activity Indicator On Main Thread
    dispatch_async(dispatch_get_main_queue(), { () -> Void in
        activityIndicator.startAnimating()
    })


    // Do your table calculation work here


    // Stop Animating Activity Indicator On Main Thread
    dispatch_async(dispatch_get_main_queue(), { () -> Void in
        activityIndicator.stopAnimating()
    })
}