使用 OperationQueue 时更新 UI

Updating UI when working with OperationQueue

我有一个操作队列设置如下:

let queue = OperationQueue()
queue.name = "com.company.myQueue"
queue.qualityOfService = .userInitiated
queue.maxConcurrentOperationCount = 64
...
var current = 0
var totalCount = someArray.count
for i in someArray {
... 
   let op = BlockOperation {
   ... // do some database queries
   current += 1
   }

   op.completionBlock = {
     DispatchQueue.main.async {
     let nData: [String: CGFloat] = ["value": CGFloat(current/totalCount)]
     NotificationCenter.default.post(name:Notification.Name(rawValue: "update"), object: nil, userInfo: nData)
   }

   queue.addOperation(op)
}

在我的 ViewController 中,我监听通知并用百分比更新 UILabel。问题是虽然我没有得到任何中间值......一旦完成所有操作,它就会从 0 直接跳到 100

我做错了什么?

谢谢

您可以直接在 op.completionBlock 中移动您的通知发送功能(无需在主线程中调度)。

编辑(评论):

let queue = OperationQueue()
    queue.name = "com.company.myQueue"
    queue.qualityOfService = .userInitiated
    queue.maxConcurrentOperationCount = 64

let array = ["", "", "", "", "", ]

var current = 0
var totalCount = array.count

for _ in array {
    let op = BlockOperation { current += 1 ; print(current) }
        op.completionBlock = {
            DispatchQueue.main.async {
                NotificationCenter.default.post(name: Notification.Name(rawValue: "update"), object: nil, userInfo: ["value": CGFloat(current / totalCount)])
            }
        }

   queue.addOperation(op)
}

NotificationCenter.default.addObserver(forName: Notification.Name(rawValue: "update"), object: nil, queue: nil) { (notification) in
    print(notification.userInfo)
}

编辑 2(评论): 您应该在除以 current 和 totalCount 之前通过 float casting 来计算百分比。

CGFloat(current) / CGFloat(totalCount)
'''

问题是CGFloat(current / totalCount)。那首先进行整数数学运算,然后将其转换为浮点数。您应该将其翻转为 CGFloat(current) / CGFloat(totalCount)