Friday, 3 July 2015

NSOperation and NSOperationQueue



The NSOperationQueue class regulates the execution of a set of NSOperation objects. After being added to a queue, an operation remains in that queue until it is explicitly canceled or finishes executing its task. Operations within the queue (but not yet executing) are themselves organized according to priority levels and inter-operation object dependencies and are executed accordingly. An application may create multiple operation queues and submit operations to any of them. 

Inter-operation dependencies provide an absolute execution order for operations, even if those operations are located in different operation queues. An operation object is not considered ready to execute until all of its dependent operations have finished executing.

You cannot directly remove an operation from a queue after it has been added. An operation remains in its queue until it reports that it is finished with its task. Finishing its task does not necessarily mean that the operation performed that task to completion. An operation can also be canceled. Canceling an operation object leaves the object in the queue but notifies the object that it should abort its task as quickly as possible. 

Operation queues usually provide the threads used to run their operations. Operation queues use the libdispatch library (also known as Grand Central Dispatch) to initiate the execution of their operations. As a result, operations are always executed on a separate thread, regardless of whether they are designated as asynchronous or synchronous operations.

Implementation of NSOperation:
1.) Create sub-class of NSOperation

Sample Code:

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@protocol DownloadOperationDelegate; // Declare delegate

@interface DownloadOperation : NSOperation
@property (nonatomic, strong) NSString *urlstring;   // declare a NSString variable
@property (nonatomic, weak) id <DownloadOperationDelegate> delegate;
-(instancetype) initWithUrlString:(NSString *)urlString andDelegate:(id<DownloadOperationDelegate>) delegate;  // Declare  a method for initialize new instance.
@end

@protocol DownloadOperationDelegate <NSObject>
//Delegate method
-(void) downloadOperation:(DownloadOperation *)operation finishedWithData:(id)result;
-(void) downloadOperation:(DownloadOperation *)operation finishedWithError:(NSError *)error;
@end

#import "DownloadOperation.h"

@implementation DownloadOperation
-(instancetype) initWithUrlString:(NSString *)urlString andDelegate:(id<DownloadOperationDelegate>)delegate{
   
    self = [super init];
    if (self != nil) {
        self.urlstring = urlString;
        self.delegate = delegate;
    }
    return self;
}

-(void) main{
    @autoreleasepool {

        if (self.cancelled) {   //return No if you cancel queue operation.
            return;
        }
        //--------------
        /*
        
             Add Code Here
        
         */
        /*
        
              After completion of define task you can notifiy by delegate method.
         if get error:
         NSError *error;
         if (error) {
         if (self.delegate && [self.delegate respondsToSelector:@selector(downloadOperation:finishedWithError:)]) {
         [self.delegate downloadOperation:self finishedWithError:error];
         }
         }
        
         Notify Task completion:
         id resultData;
         if (self.delegate && [self.delegate respondsToSelector:@selector(downloadOperation:finishedWithData:)]) {
         [self.delegate downloadOperation:self finishedWithData:resultData];
         }
        
         */
       
    }
}
@end



NOTE: Add task inside auto-release pool.

2.) Create new instance of NSOperation:
DownloadOperation *operation = [[DownloadOperation alloc] initWithUrlString:@"" andDelegate:self];

3.) Add newly created NSOperation's instance to NSOperationQueue:

NSOperationQueue *downloadQueue = [[NSOperationQueue alloc] init];//Create a instance of    NSOpearionQueue
downloadQueue.name = @"Download Database"; // Set name for created NSOperarionQueue.
downloadQueue.maxConcurrentOperationCount = 5; // Set maximum number of operations can run concurrently.
[downloadQueue addOperation:operation];//Add Operation to Operation Queue.

NOTE: You can add multiple NSOperations inside single NSOperationQueue, so no need to create multiple instance for NSOperationQueue. Just create instance of NSOperations and add inside NSOperationQueue's instance.

You can cancel ALL QUEUE OPERATIONS by:
[downloadQueue cancelAllOperations];

FOR DETAILS CLICK HERE

No comments:

Post a Comment