跟踪操作队列中的操作

Tracking operations in operation queue

我刚刚开始实现一些操作子类,它处理一些异步工作,比如为我下载。我很好奇管理队列的最佳实践,特别是为了确保我不会两次添加相同的任务。

有没有一种方法可以使用名称将操作添加到队列中,或者是创建和管理字典的情况?比如说,当项目被添加到队列中时,您将条目添加到字典中,当它们完成时,您从字典中删除条目?预先执行条件检查?

这很容易实现,因为操作子类中有一个通知块。只是看起来有点老套。

感谢您的建议。

---- 编辑 ----

所以尝试在别处使用这个 for 循环 (cellForItemAt) 来显示 activity 指示器,如果项目在队列中,但它似乎只检查队列的第一个项目,return 但没有其他即使队列中有多个具有唯一名称的操作:

            for operation in downloadQueue.operations {
                if operation.name == self.multiPartArray[collectionView.tag][indexPath.item].name  {                       innerCell.contentView.addSubview(self.activityIndicatorView)                       self.activityIndicatorView.centerXAnchor.constraint(equalTo: innerCell.contentView.centerXAnchor).isActive = true                     self.activityIndicatorView.centerYAnchor.constraint(equalTo: innerCell.contentView.centerYAnchor).isActive = true
                    self.activityIndicatorView.isHidden = false
                    self.activityIndicatorView.startAnimating()
                    innerCell.contentView.bringSubview(toFront: self.activityIndicatorView)
                    break
                } else {
                    print("Operation not in queue")
                }
            }

向队列添加操作时似乎在做同样的事情。它检查第一个操作。如果 != opName 那么它会添加操作,即使 opName 存在于队列中但不是第一项。

您可以使用操作名称来执行此操作。

let yourOperationQueue = NSOperationQueue()

每次添加操作时设置操作名称,并在每次添加操作前检查该名称。使这些操作名称保持唯一。

func addDownloadOperation()
{
    self.checkAndAddOperationWithName("DownloadOperation")
}

func addUploadOperation()
{
    self.checkAndAddOperationWithName("UploadOperation")
}

func checkAndAddOperationWithName(opName:String)
{
    var operationExist = false
    for operation in yourOpeartionQueue.operations
    {
        if operation.name == opName
        {
            print("Operation alreday added")
            operationExist = true
            break
        }
    }
    if !operationExist
    {
       self.addOperationToTheQueWithName(opName)
    }
}

func addOperationToTheQueWithName(opName:String)
{
    let someOperation = NSBlockOperation(block:{
        //some heavy operations
    })
    someOperation.name = opName
    yourOpeartionQueue.addOperation(someOperation)
    print("Operation \(opName) added")
}