操作队列如何工作?

时间:2018-07-03 12:31:46

标签: swift nsoperationqueue

我正在尝试在当前项目中实现OperationQueue。我觉得我的代码在使用旧代码时有些麻烦,但是它可以正常工作。上周,我发现了OperationQueue的相关内容,因此我尝试将其实现到我的代码中,但是我无法使其正常工作。

旧代码(有效)

UserProfileManager.shared.getColleagues(forDepartment: department) { (fetchedcolleagues) in
    if let colleagues = fetchedcolleagues {
        // Loop through colleagues
        for colleague in colleagues {
            // Unwrap mail
            guard let mail = colleague.mail else { continue }
            // Call function to get user photo
            UserProfileManager.shared.getUserPhoto(email: mail, completion: { (returnedData) in
                if let data = returnedData, let image = UIImage(data: data) {
                    colleague.addUserImage(image: image)
                }
                self.colleagueArray.append(colleague)
                // Update collectionView
                self.colleagueCollectionView.reloadData()
            })
        }
    }
}


那么首先要做的是。我的目标是:

  1. 获取有关同事的信息(包含他们的电子邮件)
  2. 使用他们的电子邮件获取用户个人资料图片
  3. 获取所有图片后,更新collectionView。

所以我试图将它们分为三个不同的块:

let queue = OperationQueue()

// First block to be done
let informationBlock = BlockOperation {
    UserProfileManager.shared.getColleagues(forDepartment: department, completion: { (fetchedColleagues) in
        if let colleagues = fetchedColleagues {
            self.colleagueArray = colleagues
        }
    })
}

// Second block to be done
let photoOperation = BlockOperation {
    for colleague in self.colleagueArray {
        guard let email = colleague.mail else { continue }

        UserProfileManager.shared.getUserPhoto(email: email, completion: { (returnedData) in
            if let data = returnedData, let image = UIImage(data: data) {
                colleague.addUserImage(image: image)
            }
            self.colleagueArray.append(colleague)
        })
    }
}
// Third block to be done
let updateOperation = BlockOperation {
    self.colleagueCollectionView.updateData()
}

updateOperation.addDependency(photoOperation)
photoOperation.addDependency(informationBlock)

queue.addOperations([informationBlock, photoOperation, updateOperation], waitUntilFinished: true)

但是上面的代码将导致:

  1. PhotoBlock(完整)
  2. UpdateBlock(完整)
  3. InformationBlock(完整)

所以问题是...我如何确保将按顺序执行块?预先感谢!

0 个答案:

没有答案