ios - 带循环的事件指示器

标签 ios multithreading swift uitableview uiactivityindicatorview

我正在使用一个应用程序,该应用程序有一个可以完成大量工作的循环。该循环生成一堆数字,然后将它们放入 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 秒内完成,但列表填充和事件指示器停止旋转需要更长的时间。我在 didWithCreateNumbers 函数中放置了一个断点,并检查了数字集合的计数,它确实包含正确的项目数。执行重新加载列表并停止事件指示器的代码后,需要 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/

相关文章:

ios - Xcode 不允许我添加 Outlets

ios - 为不同的 iPhone 调整以图像为背景的 UIButton 的大小

ios - 无法将类型 'String' 的值分配给类型 'UILabel!'

ios - 跳转到 CSV 文件中的行

ios - 根据数据更新rootview Controller

java - 在图书馆管理系统上使用多线程

swift - Swift 代码语法问题

ios - 像霍夫曼编码这样的算法是否实际用于生产?

.net - 在线程(.NET)中锁定或 try catch 字典是否更有效

c - 在队列的关键部分使用二进制信号量而不是互斥锁进行互斥有什么好处吗?