7.11. Running Tasks Synchronously with Operations


You want to run a series of tasks synchronously.


Create operations and start them manually:

@interface AppDelegate ()
@property (nonatomic, strong) NSInvocationOperation *simpleOperation;

The implementation of the application delegate is as follows:

- (void) simpleOperationEntry:(id)paramObject{
    NSLog(@"Parameter Object = %@", paramObject);
    NSLog(@"Main Thread = %@", [NSThread mainThread]);
    NSLog(@"Current Thread = %@", [NSThread currentThread]);

- (BOOL)            application:(UIApplication *)application
  didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
    NSNumber *simpleObject = [NSNumber numberWithInteger:123];
    self.simpleOperation = [[NSInvocationOperation alloc]
    [self.simpleOperation start];
    self.window = [[UIWindow alloc] initWithFrame:
                   [[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    return YES;

The output of this program (in the console window) will be similar to this:

Parameter Object = 123
Main Thread = <NSThread: 0x6810280>{name = (null), num = 1}
Current Thread = <NSThread: 0x6810280>{name = (null), num = 1}

As the name of this class implies (NSInvocationOperation), the main responsibility of an object of this type is to invoke a method in an object. This is the most straightforward way to invoke a method inside an object using operations.


An ...

Get iOS 7 Programming Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.