1

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

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用百分比更新 a。问题是虽然我没有得到任何中间值......它从0直接跳转到100所有操作完成后。

我究竟做错了什么?

谢谢

4

2 回答 2

1

您可以直接在 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 来确定您的百分比。

CGFloat(current) / CGFloat(totalCount)
'''
于 2020-05-28T15:15:05.140 回答
1

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

于 2020-05-28T15:50:57.730 回答