iOS Learning note Callbacks (ii)

Source: Internet
Author: User

Write in front

In the previous study note, we briefly introduced the callback operation via the target-action pair: Create two objects Timer and logger, set logger as the target of the timer, timer calls logger Sayouch function. In this example, the task of the timer is simple and only one task is completed: The event is triggered at the specified moment. In this case, it is appropriate to select the target-action to implement the callback, but this is not a good way to send multiple callbacks.

Helper Objects

Helper objects are another way to implement callbacks. Before the app begins to wait, a message is sent to the helper that adheres to the appropriate protocol when a specific event waits for it to occur. delegate Objects and data sources are common helper objects.

Case

Suppose we create a Nsurlconnection object and fetch the data from a given URL, and then wait for the callback. The time when the callback function is triggered includes: obtaining data, obtaining data, failing to obtain data, and so on.
It can be seen that these complex callbacks cannot be implemented if it is simply a target-action team mechanism. Therefore, we set up a helper object for the Nsurlconnection object, which is specifically responsible for dealing with what happens after a particular event, that is, when a particular event occurs, the Nsurlconnection object sends a message to the helper object. These messages are included in a set of protocols. Protocol and interface concepts are similar, and protocols are declarations of a set of methods, and classes that follow the corresponding protocols must implement the methods in the protocol (only partial methods can be implemented).
We assume that an object of the logger type becomes a helper object of the Nsurlconnection object, that is, the logger object is assigned to the member variable delegate of the Nsurlconne object. The logger class must implement a partial live method in the Nsurlconnection protocol. The diagram is as follows:

First change the code for the Logger class, because you want to receive data, so add a property of type Nsmutabledata for the logger class, as follows:
Logger.h

@property NSMutableData *incomingData;

Then implement some of the methods in the protocol in LOGGER.M

//收到一定字节数的数据后会被调用- (void)connection:(NSURLConnection *)connection    didReceiveData:(NSData *)data{    NSLog(@"received %lu bytes", [data length]);        if (!self.incomingData) {        self.incomingData = [[NSMutableData alloc] init];    }        [self.incomingData appendData: data];}//最后一部分数据处理完毕后,会被调用- (void)connectionDidFinishLoading:(NSURLConnection *)connection{    NSLog(@"Got it all!");        NSString *string = [[NSString alloc] initWithData:self.incomingData                                             encoding:NSUTF8StringEncoding];    self.incomingData = nil;    NSLog(@"string has %lu characters", [string length]);        NSLog(@"The whole string is %@", string);}//获取数据失败时,会被调用- (void)connection:(NSURLConnection *)connection  didFailWithError:(NSError *)error{    NSLog(@"connection failed: %@",[error localizedDescription]);    self.incomingData = nil;}

Create the Logger object and the nsurlconnection in the main function, and set the former to the secondary object of the latter:

Logger *logger = [[Logger alloc] init];                NSURL *url = [NSURL URLWithString:@"http://www.cnblogs.com/scut-linmaojiang/p/iOS-huidiao-y.html"];                NSURLRequest *request = [NSURLRequest requestWithURL:url];        NSURLConnection *fetchConn = [[NSURLConnection alloc]                                               initWithRequest:request                                                      delegate:logger                                              startImmediately:YES];

As shown above, when the Nsurlconnection object Fetchconn gets data from the specified URL, the Logger object is set to its helper, that is, the logger is the delegate for the Fetchconn object. Fetchcon the various states in the process of acquiring data triggers the logger execution of the corresponding state of the method. Using the breakpoint settings, we can know that normally, the order in which logger executes the callback function is:
1. Receive data, execute

- (void)connection:(NSURLConnection *)connection    didReceiveData:(NSData *)data

Run as follows:

2, the last part of the data processing completed, the implementation

- (void)connectionDidFinishLoading:(NSURLConnection *)connection

Run as follows:

...

The URL is the address of the previous note, and the data obtained is displayed in HTML format.

If the computer is processing a disconnected state, then Fetchconn will not be able to obtain the data, and logger will execute the following callback function

- (void)connection:(NSURLConnection *)connection  didFailWithError:(NSError *)error

Run as follows:

Summarize

Compare target-action pair mechanism and helper mechanism these two ways of implementing callbacks are that when an object provides only one callback function, it is more appropriate to use the target-action pair. When an object is to provide multiple callback functions, it is said that to receive multiple callback information, it is more reasonable to use a helper object that follows the corresponding protocol.

iOS Learning note Callbacks (ii)

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.