Cover by Vandad Nahavandipoor

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

5.13. Running Tasks Asynchronously with Operations

Problem

You want to execute operations concurrently.

Solution

Use operation queues. Alternatively, subclass NSOperation and detach a new thread on the main method.

Discussion

As mentioned in Recipe 5.12, operations, by default, run on the thread that calls the start method. Usually we start operations on the main thread, but at the same time we expect the operations to run on their own threads and not take the main thread’s time slice. The best solution for us would be to use operation queues. However, if you want to manage your operations manually, which I do not recommend, you can subclass NSOperation and detach a new thread on the main method. Please refer to Recipe 5.16 for more information about detached threads.

Let’s go ahead and use an operation queue and add two simple invocation operations to it. (For more information about invocation operations, please refer to this chapter’s Introduction. For additional example code on invocation operations, please refer to Recipe 5.12.) Here is the declaration (.h file) of the application delegate that utilizes an operation queue and two invocation operations:

#import <UIKit/UIKit.h> @interface Running_Tasks_Asynchronously_with_OperationsAppDelegate : UIResponder <UIApplicationDelegate> @property (nonatomic, strong) UIWindow *window; @property (nonatomic, strong) NSOperationQueue *operationQueue; @property (nonatomic, strong) NSInvocationOperation *firstOperation; @property (nonatomic, strong) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required