Asynchronous Operations | raywenderlich.com


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/9461083-ios-concurrency-with-gcd-and-operations/lessons/27

We are breaking SOLID and intended readonly state which may lead to unexpected behavior in next iOS/Xcode releases

hi! could you be more specific? thanks!

Hello again Audrey, quick question on this one. Why didn’t we append the array using a serial queue like we did in the TiltShiftOperations challenge? I actually like the fact of doing it that way so that like I believe you said this would be more thread safe by allowing only this queue to append the array serially so no other operation could append it at the same time. I guess I am to assume I should append the array serially if I think or develop an app where there might be a chance the array will be appended to elsewhere in the app?

Thanks!

let base = "https://wolverine.raywenderlich.com/books/con/image-from-rawpixel-id-"
let ids = [466881, 466910, 466925, 466931, 466978, 467028, 467032, 467042, 467052]
var images: [UIImage] = []
let queue = OperationQueue()
//Make a serial queue
let appendQueue = OperationQueue()
appendQueue.maxConcurrentOperationCount = 1

for id in ids {
  guard let url = URL(string: "\(base)\(id)-jpeg.jpg") else { continue }
  let imageLoadOp = ImageLoadOperation(url: url)
  imageLoadOp.completionBlock = {
    if let image = imageLoadOp.image {
    appendQueue.addOperation {
      images.append(image)
    }
  }
  queue.addOperation(imageLoadOp)
}

hi Kenneth! An OperationQueue maintains its own thread safety. From the documentation:

You can safely use a single OperationQueue object from multiple threads without creating additional locks to synchronize access to that object.

The images.append operations run in the order they’re added to the operation queue.