O'Reilly logo

iOS 7 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

7.16. Invoking Background Methods

Problem

You want to know an easy way to create threads without having to deal with threads directly.

Solution

Use the performSelectorInBackground:withObject: instance method of NSObject:

- (BOOL)            application:(UIApplication *)application
  didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
    
    [self performSelectorInBackground:@selector(firstCounter)
                           withObject:nil];
    
    [self performSelectorInBackground:@selector(secondCounter)
                           withObject:nil];
    
    [self performSelectorInBackground:@selector(thirdCounter)
                           withObject:nil];
    
    self.window = [[UIWindow alloc] initWithFrame:
                   [[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    return YES;
}

The counter methods are implemented in this way:

- (void) firstCounter{
    
    @autoreleasepool {
        NSUInteger counter = 0;
        for (counter = 0;
             counter < 1000;
             counter++){
            NSLog(@"First Counter = %lu", (unsigned long)counter);
        }
    }
    
}

- (void) secondCounter{
    
    @autoreleasepool {
        NSUInteger counter = 0;
        for (counter = 0;
             counter < 1000;
             counter++){
            NSLog(@"Second Counter = %lu", (unsigned long)counter);
        }
    }
    
}

- (void) thirdCounter{
    
    @autoreleasepool {
        NSUInteger counter = 0;
        for (counter = 0;
             counter < 1000;
             counter++){
            NSLog(@"Third Counter = %lu", (unsigned long)counter);
        }
    }
    
}

Discussion

The performSelectorInBackground:withObject: method creates a new thread in the background for us. This is equivalent to creating a new thread for the selectors. The most important thing we have ...

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