Need help understanding a threading issue


Rick Aurbach
 

Let me start by saying I have a solution to my problem, but would like to know why some of the other things I tried didn't work...

I have some procedures which are performed on background queues (specifically importing/exporting between a CoreData database and zipped JSON files). I want to communicate between these operations and the main queue, either to signify completion or to report an error. (I need to execute on the main queue because there is UI involved.)

My natural thought was to include the execution block in an appropriate place in an Operation's main() using

    OperationQueue.main.addOperation { [weak self] in
       ...
    }

but the the execution block was never executed. (i.e., a breakpoint on the addOperation call triggered, but a breakpoint in the execution block never triggered and the UI code in the execution block did not execute.) Replacing the OperationQueue call with DispatchQueue.main.async {...} didn't work either. The execution block was never executed.

BUT if I use NotificationCenter.default.post(...) instead, placing the operation block in

    NotificationCenter.default.addObserver(forName: <name>, object: nil, queue: OperationQueue.main) { [weak self] in
        ...
    }
then the execution block is executed and the UI code runs as expected.

While I understand why my actual solution works, I don't understand why my original attempts failed. If you could explain this to me, I would appreciate the chance to increase my understanding.

Thanks,
Rick Aurbach

Join {cocoa@apple-dev.groups.io to automatically receive all group messages.