Saturday, November 23, 2013

Using NSOperationQueue in iOS SDK

Sometimes we need to perform some task in different thread or in background. NSOperationQueue is quite handy for such purpose in iOS.

You can easily add operation you need to perform in queue just like any other object and NSOperationQueue queue will take care of its execution. You can also add operation in NSOperationQueue by specifying code block, and in many situations that's quite useful.

 Following code sample shows how we can create NSOperationQueue.
- (id)init
{
    if ((self = [super init]))
    {
        _operationQueue = [[NSOperationQueue alloc] init];
        //[_operationQueue setMaxConcurrentOperationCount:1];
    }
    return self;
}

- (void)dealloc
{
    [_operationQueue release];
    [super dealloc];
}

Below code shows how we can add operation to NSOperationQueue by code block.
- (void)requestFinished:(ASIHTTPRequest *)request {
        
    [_operationQueue addOperationWithBlock:^{
        
        //perform some useful task
        
    }];
}
   -(void) processEntries:(NSArray*) entries
   {
   }

   [_operationQueue addOperationWithBlock:^{
     [self processEntries:entries];
   }];

No comments:

Post a Comment