Redjimi Adel Redjimi Adel - 3 months ago 21
Swift Question

NSOperationQueue not finishing operations?

I started learning multi-threading in Swift lately, and I wanted to try some basic multi-threading using the

NSOperationQueue
and
NSOperation
classes.

On the global scope of a .swift file (on a Command Line Tool project in Xcode), I defined these two functions :

func foo() { /* prints from 1 to 26 */ }
func bar() { /* prints from a to z */ }


then I instantiated an NSOperationQueue and did the following :

let queue = NSOperationQueue()
queue.addOperationWithBlock(foo)
queue.addOperationWithBlock(bar)


I run the program and got no output. Why?

I try printing some output outside the queue, on what's supposed to be the main thread, the global scope in this example so I did this :

print("START")

let queue = NSOperationQueue()
queue.addOperationWithBlock(foo)
queue.addOperationWithBlock(bar)

print("END")


And got an output "like" this :

START
END
0
1


it seems like operations on the queue aren't executed properly. The main thread isn't waiting for the queue to finish?

Rob Rob
Answer

You're not seeing your output because the command line app is finishing before the operations added to the queue had a chance to finish. The entire purpose for adding operations to a NSOperationQueue is to perform some tasks on some other thread, often expressly for the purpose of not blocking the main thread while initiating something time consuming.

You theoretically can wait for all of the operations to finish (see waitUntilAllOperationsAreFinished), but while that's a pattern useful in your command line test, but you would almost never use in Cocoa or Cocoa Touch app (because we never want to block the main thread in those environments).