// 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:
Thank you ,it was quite clear about NSOperation & NsOperationQueue.
Post a Comment