Challenge: Download Images in OperationQueue |

This is a companion discussion topic for the original entry at

Something I don’t understand about the subclass “ImageLoadOperation” is that it has an overridden method called main, but I don’t see where it actually gets called from within the for loop.

Also… the “AsyncOperation” class has a start() method, but I also don’t see that called from within the ImageLoadOperation class.

I’m confused!

hi Jason! it’s the magic of OperationQueue: when you add an operation to an operation queue, the operation queue manages execution. For example, if the operation depends on another operation, the queue won’t start it until the other operation finishes.

One question here about your placement of these two lines of code inside of the URLSession.shared.dataTask’s completionBlock:

  1. guard let self = self else { return }
  2. defer { self.state = .finished }

Should those two be flipped? I’m imagining a scenario where a VC disappears and therefore we exit before setting state to finished. If the operationQueue is held onto and managed elsewhere, that would result in a blocked queue. Does that sound right or am I missing something?

hi Joe! good question … but self here is the operation so if it’s gone, you don’t need to mark it finished. In fact, you can’t set its state to finish if there’s no self.

when we get to canceling operations, you’ll add code to cancel an operation when its cell goes off screen.

You’d think that the self before state would have told me that, but alas…

Thank you! Your videos have been some of my favorites.

1 Like

Why do you not required to seralize the image append this time? shouldn’t this to be put in a serial queue? append seems not thread safe

hi Bolun Qi, thanks for your question!

this is just a simple append — the examples I’ve found of race conditions when you append to an array involve appending at a specific index. If you don’t use a serial queue, this can lead to one append task over-writing another.