Using NSOperationQueue in iOS to do Serial/Concurrent Operations.

By | May 4, 2016

NSOperationQueue is used to do scheduled operations in iOS. You can customize NSOperationQueue to do Concurrent/Serial operations.

You can set NSOperationQueue maxConcurrentOperationCount to tell it to do how many operations to execute at a time.

Lets see this with an example

[Swift Version]

import UIKit
 
class ViewController: UIViewController {
 
    override func viewDidLoad() {
        super.viewDidLoad()
         
        let downloadQueue = NSOperationQueue();
        downloadQueue.maxConcurrentOperationCount = 1;
         
        for i in 1...10 {
             
            let operation : NSBlockOperation = NSBlockOperation(block: {
                 self.downloadImage(i)
            })
             
            downloadQueue.addOperation(operation);
        }
         
         
    }
 
     
    func downloadImage (index : Int){
         
        print("Download Started \(index)")
        sleep(2);
        print("Download Complete \(index)")
    }
 
}

In the above example, we set maxConcurrentOperationCount to 1, telling it to execute one by one.

[Objective C Version]

#import "ViewController.h"
 
@interface ViewController ()
 
@end
 
@implementation ViewController
 
- (void)viewDidLoad {
     
    [super viewDidLoad];
     
    // Create a new NSOperationQueue instance.
    operationQueue = [NSOperationQueue new];
    operationQueue.maxConcurrentOperationCount = 1;
     
    for(int i = 0; i < 10; i++){
         
        NSNumber* iParam = [NSNumber numberWithInt:i];
     
        // Create a new NSOperation object using the NSInvocationOperation subclass.
        NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self
                                                                                selector:@selector(downloadImage:)
                                                                                  object:iParam];
        // Add the operation to the queue and let it to be executed.
        [operationQueue addOperation:operation];
    }
     
}
 
-(void) downloadImage : (NSNumber *) index{
     
    NSLog(@"Download Started %d", index.intValue);
    sleep(2);
    NSLog(@"Download Complete %d", index.intValue);
}
 
@end

With this you can schedule your operations so give a better user experience to the user.

You can send your valuable comments to coderzheaven@gmail.com.

Leave a Reply

Your email address will not be published. Required fields are marked *