gpt4 book ai didi

ios - 带循环的事件指示器

转载 作者:搜寻专家 更新时间:2023-11-01 07:30:01 25 4
gpt4 key购买 nike

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

    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)
});

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

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

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

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

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

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()
})
}

关于ios - 带循环的事件指示器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33139406/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com