Search code examples
iosmultithreadinggrand-central-dispatchnsoperationnsoperationqueue

iOS correct use of multithreading


I would like to know how to use multithreading in iOS. I am aware of GCD and NSOperationQueue, but I am not sure how to use them properly.

  1. When should I use GCD/NSOperationQueue?
  2. How do I cancel a queue if the view for the results are no longer in view? (i.e. send a request for something, but user then decides to hit the back button to go to another view, which means I no longer require that "something")

Any examples will be greatly appreciated.

Thank you.


Solution

  • It's probably worth mentioning that once an operation has started (either a GCD block or an NSOperation) you can only cancel it if cancel-ability is built into the operation itself. For instance, NSOperation has an -cancel method, but that only works if your operation is periodically checking the -isCanceled flag from inside the operation, and then returning early if it sees that the operation has been cancelled. From the docs for -[NSOperation cancel]:

    This method does not force your operation code to stop. Instead, it updates the object’s internal flags to reflect the change in state. If the operation has already finished executing, this method has no effect. Canceling an operation that is currently in an operation queue, but not yet executing, makes it possible to remove the operation from the queue sooner than usual.

    Likewise a GCD block can check some shared flag and return early, but neither of these mechanisms are capable of force-canceling an operation. The reason for this is that if you were able to force-cancel the operation, it would have no chance to clean itself up, thus any memory allocated during the task would be leaked.

    One other common way around this limitation is to divide your tasks into many more smaller operations such that the time for a single operation to complete is small enough to be negligible. This gives you the ability to suspend/cancel the queue/NSOperationQueue at the whole-queue level and achieve approximately the desired effect.