NSOperation and NSOperationQueue working thread vs main thread NSOperation and NSOperationQueue working thread vs main thread ios ios

NSOperation and NSOperationQueue working thread vs main thread


My question is whether the database write operation occur in main thread or in a background thread?

If you create an NSOperationQueue from scratch as in:

NSOperationQueue *myQueue = [[NSOperationQueue alloc] init];

It will be in a background thread:

Operation queues usually provide the threads used to run their operations. In OS X v10.6 and later, operation queues use the libdispatch library (also known as Grand Central Dispatch) to initiate the execution of their operations. As a result, operations are always executed on a separate thread, regardless of whether they are designated as concurrent or non-concurrent operations

Unless you are using the mainQueue:

NSOperationQueue *mainQueue = [NSOperationQueue mainQueue];

You can also see code like this:

NSOperationQueue *myQueue = [[NSOperationQueue alloc] init];[myQueue addOperationWithBlock:^{   // Background work    [[NSOperationQueue mainQueue] addOperationWithBlock:^{        // Main thread work (UI usually)    }];}];

And the GCD version:

dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void)             {              // Background work                         dispatch_async(dispatch_get_main_queue(), ^(void)              {                   // Main thread work (UI usually)                                        });});

NSOperationQueue gives finer control with what you want to do. You can create dependencies between the two operations (download and save to database). To pass the data between one block and the other, you can assume for example, that a NSData will be coming from the server so:

__block NSData *dataFromServer = nil;NSBlockOperation *downloadOperation = [[NSBlockOperation alloc] init];__weak NSBlockOperation *weakDownloadOperation = downloadOperation;[weakDownloadOperation addExecutionBlock:^{ // Download your stuff   // Finally put it on the right place:  dataFromServer = .... }];NSBlockOperation *saveToDataBaseOperation = [[NSBlockOperation alloc] init];__weak NSBlockOperation *weakSaveToDataBaseOperation = saveToDataBaseOperation; [weakSaveToDataBaseOperation addExecutionBlock:^{ // Work with your NSData instance // Save your stuff }];[saveToDataBaseOperation addDependency:downloadOperation];[myQueue addOperation:saveToDataBaseOperation];[myQueue addOperation:downloadOperation];

Edit: Why I am using __weak reference for the Operations, can be found here. But in a nutshell is to avoid retain cycles.


If you want to perform the database writing operation in the background thread you need to create a NSManagedObjectContext for that thread.

You can create the background NSManagedObjectContext in the start method of your relevant NSOperation subclass.

Check the Apple docs for Concurrency with Core Data.

You can also create an NSManagedObjectContext that executes requests in its own background thread by creating it with NSPrivateQueueConcurrencyType and performing the requests inside its performBlock: method.


From NSOperationQueue

In iOS 4 and later, operation queues use Grand Central Dispatch to execute operations. Prior to iOS 4, they create separate threads for non-concurrent operations and launch concurrent operations from the current thread.

So,

[NSOperationQueue mainQueue] // added operations execute on main thread[NSOperationQueue new] // post-iOS4, guaranteed to be not the main thread

In your case, you might want to create your own "database thread" by subclassing NSThread and send messages to it with performSelector:onThread:.