Wednesday, September 29, 2010

Introduction to NSOperation and NSOperationQueue

Hi,

NSOperation is a class by using this we can execute chunk of code which is identical and it doesn't have any direct relationship with other component in the project.

In other words, we can create a specific job by using NSOperation. for example we need to write a buffer into file normally we will use thread, in cocoa another feature is NSOperation and NSOperationQueue. NSOperationQueue is also going to create thread but it makes life easier to the programmer.

NSOperation
developer can create new class by inheriting NSOperation. This class should contain a main method, whenever we add an operation to NSOperationQueue it will call main method of NSOperation class. So developer can start writing his job in main method.


// NSOperationExtended.h

#import



@interface NSOperationExtended : NSOperation {

NSString *name;

}


@property (retain)NSString* name;


@end



// NSOperationExtended.m

#import "NSOperationExtended.h"


static NSLock *lock;

@implementation NSOperationExtended

@synthesize name;


-(id) initWithName:(NSString*) string

{

if(!lock)

{

NSLog(@"NSLock Object creation");

lock = [[NSLock alloc] init];

}

if (self = [super init])

{

self.name = string;

return self;

}

return nil;

}


-(void) main

{

[lock lock];

sleep(3);

NSLog(@"NSOperation scheculed for %@", self.name);

NSLog(@"thread id = %@", [NSThread currentThread]);

sleep(2);

[lock unlock];

}



@end



NSOperationExtended is a class which inherits NSOperation and we override main method because NSOperationQueue is going to call NSOperation's main method.


Now we will discuss about how to add this object to NSOperationQueue.




NSMutableArray *array = [[NSMutableArray alloc] init];

[array addObject:@"Operation one"];

[array addObject:@"Operation Two"];

[array addObject:@"Operation Three"];

[array addObject:@"Operation Four"];

[array addObject:@"Operation Five"];


NSOperationQueue *queue;

queue = [[NSOperationQueue alloc] init];


for (NSString *urlString in array)

{

NSOperationExtended *jobComponent= [[NSOperationExtended alloc] initWithName:urlString];

[queue addOperation: jobComponent];

[jobComponent release];

}


[queue addOperation: jobComponent];


This above line is responsible for calling main of NSOperationExtended method.




1 comment:

Anonymous said...

Thank you ,it was quite clear about NSOperation & NsOperationQueue.