O'Reilly logo

iOS 5 Programming Cookbook 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

5.12. Running Tasks Synchronously with Operations

Problem

You want to run a series of tasks synchronously.

Solution

Create operations and start them manually:

#import <UIKit/UIKit.h>

@interface Running_Tasks_Synchronously_with_OperationsAppDelegate
           : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;
@property (nonatomic, strong) NSInvocationOperation *simpleOperation;

@end

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]
                          initWithTarget:self
                          selector:@selector(simpleOperationEntry:)
                          object:simpleObject];
  
  [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 ...

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