Block-based value transfer and block-based encapsulation of a network request class

Source: Internet
Author: User
1. The block transmits values between the two uiviewcontrollers.

Recently, I have just learned a few advanced block usage methods. In fact, I used the block syntax to pass values between two uiviewcontrollers. Here I will share this with beginners and help me understand it myself. We know that when the uinavigationcontroller class manages uiviewcontroller, we use the "stack" idea. Here we will not explain it too much and start with the topic. Suppose we have two uiviewcontroller, viewc1, and viewc2, viewc1 is more advanced than viewc2 into uinavigationcontroller, that is, viewc2 is pushed by viewc1. here, the value is transmitted to viewc1. For example, modify the address book and modify the information in the address book.

Not to mention, let's look at the following example:

I. First, the code in the header file of viewc2 is as follows:

// 1. Redefinition of a block type typedef void (^ BL) (uicolor * color); typedef void (^ stringbl) (nsstring * string); @ interface secondviewcontroller: uiviewcontroller // you must use the copy feature to define a block attribute. Cause: @ property (nonatomic, copy) BL block; @ property (nonatomic, copy) stringbl string;-(void) valueblock :( BL) block;-(void) valuestringblock :( stringbl) block;
Tip:

Redefinition of block has a shortcut Implementation Method in xcode. If typedef is typed directly on @ interfacexxx, a prompt will be displayed: Press enter. The first parameter is the return value type, and the second is the name of the redefined block, the third is to pass in the parameter type and parameter name. Then, you need to define the attributes of the block type and implement the parameter method for this type block.

Ii. Code in the. M file of viewc2:

-(Void) viewdidload {[Super viewdidload]; // do any additional setup after loading the view. uibutton * button = [uibutton buttonwithtype: uibuttontypesystem]; button. frame = cgrectmake (0, 70,320, 40); [self. view addsubview: button]; [Button settitle: @ "return 1 page" forstate: uicontrolstatenormal]; [Button addtarget: Self action: @ selector (buttonaction :) forcontrolevents: uicontroleventtouchupinside];} -(void) buttonaction :( uibutton *) button {// 2. execute the block code self. block ([uicolor redcolor]); self. string (@ "asdasdasd"); [self. navigationcontroller poptorootviewcontrolleranimated: Yes];}-(void) valueblock :( BL) block {self. block = block;}-(void) valuestringblock :( stringbl) block {self. string = block ;}
Explanation: implements the methods defined in the header file. The method internally assigns parameters to the attributes of the re-defined block, and then executes the block code in the appropriate place, the parameters in the block are the values you want to pass.

3. Call the viewc2 method when pushing the second page in viewc1 and press enter directly. The parameter name in the block redefinition is the value to be modified in viewc1.


2. Use block to encapsulate network request classes. 1. Create a network request class netrequest. the header file is as follows:
typedef void(^BLOCK)(id result);@interface NetRequest : NSObject@property (nonatomic, copy) BLOCK bl;- (void)requestNetWithUrl:(NSString *)urlStr BodyOfRequestForString:(NSString *)bodyStr block:(BLOCK)bl;+ (void)PostWithUrl:(NSString *)urlStr BodyOfRequestForString:(NSString *)bodyStr block:(BLOCK)bl;@end
Explanation: This method uses asynchronous post to transfer values. The header file is basically the same as the block to transfer values. I have written a + method here, in order to make it easier to use the netrequest class. We can see that the method here has three parameters, namely the URL address and the httpbody attribute of the request. This is a network request and will not be explained too much. 2. See the. M file below: Implement two methods
- (void)requestNetWithUrl:(NSString *)urlStr BodyOfRequestForString:(NSString *)bodyStr block:(BLOCK)bl{    self.bl = bl;    NSURL *url = [NSURL URLWithString:urlStr];    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];    request.HTTPMethod = @"post";    NSData *bodyData = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];    request.HTTPBody = bodyData;    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {       NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options :NSJSONReadingMutableContainers error:nil];        NSLog(@"%d", [[dic objectForKey:@"news"] count]);        self.bl(dic);        }];    }+ (void)PostWithUrl:(NSString *)urlStr BodyOfRequestForString:(NSString *)bodyStr block:(BLOCK)bl{    NetRequest *netRequest = [[NetRequest alloc] init];    [netRequest requestNetWithUrl:urlStr BodyOfRequestForString:bodyStr block:bl];}
Explanation:-In the method, you must first set the attribute block = parameter block, and then add the value to be passed to the parameters of the block method. + The "-" method is used to pass the parameter block to the attribute block. Because you cannot directly assign values to attributes in the + method.
3. How to Use: transmit data to viewcontroller
-(ID) initwithnibname :( nsstring *) nibnameornil bundle :( nsbundle *) attributes {self = [Super initwithnibname: nibnameornil Bundle: Signature]; If (Self) {// custom initialization self. array = [nsmutablearray array]; self. title = @ "news"; nsstring * urlstr = @ "http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx "; nsstring * bodystr = @ "date = 20131129 & startrecord = 1 & Len = 30 & udid = 1234567890 & terminaltype = iPhone & cid = 213"; [netrequest postwithurl: urlstr bodyofrequestforstring: bodystr block: ^ (ID result) {self. array = [result objectforkey: @ "news"]; [self. tableview reloaddata];} return self;}-(void) viewdidload {[Super viewdidload]; // do any additional setup after loading the view. self. tableview = [[uitableview alloc] initwithframe: cgrectmake (0, 0,320,480) style: uitableviewstyleplain]; [self. view addsubview: Self. tableview]; self. tableview. datasource = self; self. tableview. delegate = self; [self. tableview registerclass: [uitableviewcell class] forcellreuseidentifier: @ "reuse"];}-(uitableviewcell *) tableview :( uitableview *) tableview cellforrowatindexpath :( nsindexpath *) indexpath {nsstring * STR = @ "reuse"; uitableviewcell * cell = [tableview dequeuereusablecellwithidentifier: Str]; cell. textlabel. numberoflines = 2; cell. textlabel. TEXT = [[self. array objectatindex: indexpath. row] objectforkey: @ "title"]; return cell;}-(void) tableview :( uitableview *) tableview didselectrowatindexpath :( nsindexpath *) indexpath {webviewcontroller * webvc = [[webviewcontroller alloc] init]; webvc. weburl = [[self. array objectatindex: indexpath. row] objectforkey: @ "newsurl"]; [self. navigationcontroller pushviewcontroller: webvc animated: Yes]; [webvc release];}-(nsinteger) tableview :( uitableview *) tableview numberofrowsinsection :( nsinteger) Section {return [self. array count];}


Next let's take a look at why we need to use this value transfer method: Because I want to transmit the current data to a uiviewcontroller, and this uiviewcontroller has a uitableview and needs to be refreshed, when we obtain network data, we use a block encapsulation method to obtain nsdata. This method will execute block statements after the data is loaded, and there will be network latency, our UI will give priority to the display of data on the mobile phone. Therefore, when the data request is successful, we need to refresh the page, that is, call the reloaddata method of uitableview, so this policy is used.

This is a new get skill today. I am a newbie here. I hope you can get your guidance if you have any of the above questions. Thank you!

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.