How to customize a nsoperation

Source: Internet
Author: User

The Foundation framework provides a subclass of two built-in nsoperation, but these two built-in operation do not necessarily meet our actual needs. For example, we need a operation to complete a network request, there may be many custom logic inside, in order to complete these unique logic, often need to customize a nsoperation subclass.


The Nsoperation class itself implements many customizations related things, we only need to do a relatively small amount of work, it is relatively simple to customize a non-concurrent operation, only need to deal with the logic needed to do, and handle the cancel operation can be, the others do not need to do. But customizing a concurrency operation is relatively difficult, and there are more things to do.

IF The block operation and invocation operation objects do not quite meet the needs of your application, can subclass Nsoperation directly and add whatever behavior you need. The Nsoperation class provides a general subclass point for all Operation objects. The class also provides a significant amount of infrastructure to handle most of the work needed for dependencies and KVO Notifications. However, there may still is times when you need to supplement the existing infrastructure to ensure that your operations B Ehave correctly. The amount of extra work for you has to does depends on whether you is implementing a nonconcurrent or a concurrent operation.


Defining a nonconcurrent operation is much simpler than defining a concurrent operation. For a nonconcurrent operation, all of the perform your main task and respond appropriately to cancellation even Ts The existing class infrastructure does all of the same work for you. For a concurrent operation, you must replace some of the existing infrastructure with your custom code. The following sections show how to implement both types of object.


Performing the Main Task

Whatever the type of operation, one thing that must be done is to execute the required task, which is the most basic meaning of operation existence.


At a minimum, every operation object should implement at least the following methods:

1, A Custom initialization method


2. Main


You need a custom initialization method to put your operation object in a known state and a custom main method to Perfor M your task. You can implement additional methods as needed, of course, such as the following:


1, Custom methods that you plan to call from the implementation of your main method.


2. Accessor methods for setting data values and accessing the results of the operation.


3. Methods of the Nscoding protocol to the archive and unarchive the Operation object.


The following code shows a starting template for a custom nsoperation subclass. (This listing does isn't show how to handle cancellation and does show the methods you would typically has. For information on handling cancellation, see "Responding to cancellation Events") The initialization method for this C Lass takes a single object as a data parameter and stores a reference to it inside the Operation object. The main method would ostensibly work in that data object before returning the results back to your application.


Defining a simple Operation object.


@interface mynonconcurrentoperation:nsoperation

@property ID (strong) MyData;


-(ID) Initwithdata: (ID) data;


@end


@implementation Mynonconcurrentoperation

-(ID) Initwithdata: (ID) Data {

if (self = [super init]) {

MyData = data;

}


return self;

}


-(void) Main {

@try {

Do some work on myData and report the results.

@catch (...) {

Do not rethrow exceptions.

}

}



@end


For a detailed example of what to implement an nsoperation subclass, see Nsoperationsample.


In addition to adding the main method that must work, you must also handle the cancel-related logic, and support Cancel is a very important part of Nsoperation's ability to do so.


Responding to cancellation Events


After a operation begins executing, it continues performing its task until it is finished or until your code explicitly c Ancels the operation. Cancellation can occur at no time, even before an operation begins executing. Although the Nsoperation class provides a-clients to cancel an operation, recognizing the cancellation event is VO Luntary by necessary. If an operation were terminated outright, there might isn't be a-to-reclaim resources that had been allocated. As a result, operation objects is expected to check for cancellation events and to exit gracefully when they occur in the Middle of the operation.


To support cancellation a Operation object, all of which have a to do are call the object ' s iscancelled method periodically fr Om your custom code and return immediately if it ever returns YES. Supporting cancellation is important regardless of the duration for your operation or whether you subclass nsoperation dire ctly or use one of its concrete subclasses. The IsCancelled method itself is very lightweight and can being called frequently without any significant performance penalty . When designing your Operation objects, you should consider calling the Iscalled method at the following places in your cod E:


1, Immediately before you perform any actual work.


2, at least once during each iteration of a loop, or more frequently if each iteration is relatively long.


3, at any points in your code where it Woul is relatively easy to abort the operation.


The following provides a very simple example of what to respond to cancellation events in the main method of a operation O Bject. In this case, the IsCancelled method was called each time through a while loop, allowing for a quick exit before work begin S and again at regular intervals.


Responding to a cancellation request

-(void) Main {

@try {

BOOL isDone = NO;


while (![ Self iscancelled] &&!isdone) {

Do some work and set IsDone to YES when finished

}

} @catch (...) {

Do not rethrow exceptions.

}

}


Although the preceding example contains no cleanup code, your own code should be sure llocated by your custom code.










How to customize a nsoperation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.