Block for iOS development achieves same asynchronous loading

Source: Internet
Author: User

Block for iOS development achieves same asynchronous loading

1. Related Knowledge

1. Control Layer

Responsible for data interaction. The control layer requests data and creates an object with network requests. The object contains a block, which calls back the requested data to the control layer.

2. Data transmission process

Request (after data is requested) calls back to the Controller

 

Ii. synchronous data loading

Thoughts:

The Request object downloads network data. the data to be downloaded in the Controller, but directly implementing the download function in the Controller is not a good habit. implement the download function in the Request, set the block attribute, and call back the downloaded data to the Controller (provided that the Controller implements the block ). define a Request object in the Controller to download data. after the data is downloaded, a block is executed, and the block is implemented in the Controller. Therefore, the downloaded data can be used in the Controller.

 

Request. h // the data Request is responsible for loading data and calling back the loading information to the Controller through the block.
# Import
 
  
@ Interface Request: NSObject // data is responsible for storing the requested data error. It is responsible for storing the information about Operation errors. The user-friendly feature design // provides the user with failure information when the function fails. @ property (nonatomic, copy) void (^ block) (NSData * data, NSError * error); // network download method-(void) requestDataFromUrl :( NSString *) url; @ end
 

Requset.m
# Import Request. h @ implementation Request @ synthesize block = _ block;-(void) dealloc {[_ block release]; [super dealloc];}-(void) requestDataFromUrl :( NSString *) url {// network address NSURL * URL = [NSURL URLWithString: url]; // download data NSData * data = [NSData dataWithContentsOfURL: URL] through the network address; // return data through block @ try {// NORMAL Data Request // 1. the requested data is not empty // 2. the request itself is an empty if (nil! = Data) {// call the block to return data to self normally. block (data, nil);} else {// if the data is null, The NSError * error = [[NSError alloc] initWithDomain: @ indicates that the requested data is empty. code: 404 userInfo: nil]; self. block (nil, error); [error autorelease] ;}}@ catch (NSException * exception) {// when a network request fails, // exception is thrown. When the network request itself fails, the Operation Failure NSError * error = (NSError *) exception is included. self. block (nil, error) ;}}@ end

Controller.h
# Import Controlller. h # import Request. h @ implementation Controlller {Request * _ request;}-(void) viewDidLoadWithURL :( NSString *) url {// assign a value to the network attribute _ request = [[Request alloc] init]; // prepare for receiving callback data // 1. create block 2. point the request block to the created block _ request. block = ^ (NSData * data, NSError * error) {if (nil! = Data) {NSString * str = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding]; NSLog (, str); [str release];} else {NSLog (% @, error. localizedDescription) ;}}; [_ request requestDataFromUrl: url] ;}- (void) dealloc {[_ request release]; [super dealloc] ;}@ end
Controller.m
# Import Controlller. h # import Request. h @ implementation Controlller {Request * _ request;}-(void) viewDidLoadWithURL :( NSString *) url {// assign a value to the network attribute _ request = [[Request alloc] init]; // prepare for receiving callback data // 1. create block 2. point the request block to the created block _ request. block = ^ (NSData * data, NSError * error) {if (nil! = Data) {NSString * str = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding]; NSLog (, str); [str release];} else {NSLog (% @, error. localizedDescription) ;}}; [_ request requestDataFromUrl: url] ;}- (void) dealloc {[_ request release]; [super dealloc] ;}@ end

Main Function
# Import
 
  
# Import Controlller. h # define URL @ http://Mrshang110.local/Demo/1.txtint main (int argc, const char * argv []) {@ autoreleasepool {// create the object Controlller * ctr = [[Controlller alloc] init]; // call the interface [ctr viewDidLoadWithURL: URL]; [ctr release];} return 0 ;}
 

Iii. asynchronous loading

 

 

# Import
 
  
# Import Controller. h # define URL @ http://Mrshang110.local/Demo/1.txtint main (int argc, const char * argv []) {@ autoreleasepool {Controller * ctr = [[Controller alloc] init]; [ctr viewDidLoadWithUrl: URL]; [ctr release]; sleep (1) ;}return 0 ;}# import
  
   
@ Interface Controller: NSObject-(void) viewDidLoadWithUrl :( NSString *) url; @ end # import Controller. h # import Request. h @ implementation Controller {Request * _ request;}-(void) viewDidLoadWithUrl :( NSString *) url {if (nil = _ request) {_ request = [[Request alloc] init];} _ request. block = ^ (NSData * data, NSError * error) {if (nil! = Data) {NSString * str = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding]; NSLog (, str); [str release];} else {NSLog (% @, error. localizedDescription) ;}}; [_ request requestDataWithUrl: url] ;}- (void) dealloc {[_ request release]; [super dealloc] ;}@ end # import
   
    
@ Interface Request: NSObject @ property (nonatomic, copy) void (^ block) (NSData * data, NSError * error); // declare a method for data download-(void) requestDataWithUrl :( NSString *) url; @ end # import Request. h @ implementation Request @ synthesize block = _ block;-(void) requestDataWithUrl :( NSString *) url {NSURL * URL = [NSURL URLWithString: url]; // create a sub-thread to request data. The request is returned to the main thread. // NSThread Thread class. Its object is a sub-thread. The sub-thread can be independent from the main thread to notify the main thread of the result // both the main thread and the sub-thread Execute Line NSThread * thread = [[NSThread alloc] initWithTarget: self selector: @ selector (download :) object: URL]; // download is a method with parameters. Its network request is fixed to URL // create thread-based thread to execute the object method of the current class download // download data from the target thread /* start the sub-thread */[thread start];} -(void) download :( NSURL *) url {// code to be executed by sub-thread // Number of NSData storage downloads NSData * data = [NSData dataWithContentsOfURL: url]; // process the requested data @ try {// normal data returns if (nil! = Data) {self. block (data, nil);} else {NSError * error = [[NSError alloc] initWithDomain: @ the request data is empty. code: 404 userInfo: nil]; self. block (nil, error) ;}@catch (NSException * exception) {// NSError * error = (NSError *) exception when the network request itself is incorrect; self. block (nil, error) ;}}-(void) dealloc {[_ block release]; [super dealloc] ;}@ end
   
  
 


 

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.