iOS to implement block description

Source: Internet
Author: User
Tags uikit


Source code Download

Talking about how to use block

For block he is really convenient, a lot of people are very confused, here wrote a demo explain how to use the block

A lot of people think that block is used for the next interface to pass the value of the previous interface, in fact, in more detail is often used to interface between the value, In fact, it is only necessary to pass the value, whether it is between the view and controller or between the view and controller can use block, when the value is less than the use of block than proxy more convenient.

Blocks are stored in the stack after the creation, the semantics of the block must be copied, by copy can be the block from the stack to the heap area, to ensure that block every time the use of block exists, so we often use to define the property, using the property is to save the block variable

For example, here is a sample explanation

First create two classes of Blockviewcontroller and Blockview in Project

In Blockview, just to create a few buttons to use in Blockviewcontroller , you can reduce the amount of Blockviewcontroller code Tasks, However, there is only one instance variable button in Blockview, which is defined in the extension and cannot be interviewed externally, when we need to get the tag value of the button when we add a click Trigger event for the button, we get the tag of the button clicked, To add a response event to a different button


Define a block variable and a method in Blockview. h, the parameter of the method is the block type

#import <uikit/uikit.h>//First step: Declare blocktypedef void (^buttonactionblock) (Nsinteger tag); @interface Blockview: uiview-(void) Buttonactionblock: (Buttonactionblock) Didclickbutton; @end

In the BLOCKVIEW.M
<pre name= "code" class= "OBJC" > #import "BlockView.h" @interface Blockview ()//block//block are stored in the stack after creation, The semantic nature of block must be copy, which allows the block to be placed from the stack to the heap area by copy, ensuring that the block exists @property (nonatomic, copy) every time the block is used Buttonactionblock Buttonactionblock; @property (nonatomic, strong) UIButton *button; @end @implementation blockview-(ID) initWithFrame: (    CGRect) frame{self = [super Initwithframe:frame];        if (self) {cgfloat x = 5;        CGFloat y = 5;        CGFloat width = 65;        CGFloat height = 40; Create a button for (int i = 0; i < 4; i + +) {Self.button = [UIButton buttonwithtype: (Uibuttontypesystem)            ];            Self.button.frame = CGRectMake (x + i * (width + ten), Y, width, height);            Self.button.tag = + i;            Self.button.backgroundColor = [Uicolor Cyancolor];            Self.button.layer.cornerRadius = 5;            Self.button.layer.masksToBounds = YES; [Self.button settitle:[nsstring stringwithformat:@ "%d", I] Forstate:uicontrolstatenorMAL];            [Self.button addtarget:self Action: @selector (Handlebutton:) forcontrolevents:uicontroleventtouchupinside];        [Self Addsubview:_button]; }} return self;} Handles the button's click event, passing the tag value to block's parameter callback block-(void) Handlebutton: (UIButton *) button{NSLog (@ "???????????????    3 ");   Nsinteger tag = Button.tag; The second step, back off block  self.buttonactionblock (tag), NSLog (@ "???????????????    6 "); NSLog (@ "???????????????    7 "); }//Self.buttonactionblock = Didclickbutton In this method, the setter method of the property Buttonactionblock is called after the run. Pass the block variable Didclickbutton to the Setter method's argument-(void) Buttonactionblock: (buttonactionblock) didclickbutton{NSLog (@ "???????????????    1 ");    NSLog (@ "-----------Didclickbutton =%p", Didclickbutton);    Self.buttonactionblock = Didclickbutton; }//overrides the setter method of the property Buttonactionblock, which overrides the setter method in order to show that the method is a deep copy of the passed block variable, copied to the heap area, and assigned to the instance variable Buttonactionblock, So that we can use the block variable at any time (after the block is created in the stack, the method is recycled and can no longer be used)-(void) Setbuttonactionblock: (Buttonactionblock) buttonactionblock{NSLog (@ "???????????????    2 ");        if (_buttonactionblock! = Buttonactionblock) {NSLog (@ "++++++++buttonactionblock =%p", buttonactionblock);    _buttonactionblock = [Buttonactionblock copy]; }} @end


blockviewcontroller. m file Import BlockView.h file

blockviewcontroller. m files in code implementation

#import "BlockViewController.h" #import "BlockView.h"//Get RGB color # define RGBA (r,g,b,a) [Uicolor colorwithred:r/255.0f green:g/255.0f blue:b/255.0f alpha:a] @interface blockviewcontroller () <UIScrollViewDelegate> @property ( Nonatomic, strong) Uiimageview *yjfimageview; @end @implementation blockviewcontroller-(ID) initwithnibname: (NSString    *) Nibnameornil Bundle: (NSBundle *) nibbundleornil{self = [super Initwithnibname:nibnameornil Bundle:nibbundleornil]; if (self) {} return to self;}    -(void) viewdidload{[Super Viewdidload];    Self.view.backgroundColor = RGBA (252, 230, 201, 1.0);    Blockview *blockview = [[Blockview alloc] Initwithframe:cgrectmake (10, 0, 320-20, 50)];    Blockview.backgroundcolor = [Uicolor Lightgraycolor];    [Self.view Addsubview:blockview]; Blockview Object Blockview calls its method Buttonactionblock://Third step. Call block  [Blockview buttonactionblock:^ (Nsinteger tag) {//block implementation NSLog (@ "???????????????        4 ");  [Self handlebutton:tag];      NSLog (@ "???????????????            5 ");    }]; [Self CreateView];}        Handle the Click event of your own definition toolbar-(void) Handlebutton: (nsinteger) tag{switch (tag) {//...button Case 100: {self.        Yjfimageview.image = LoadImage (@ "2", @ "jpg");                        } break; ... button case 101: {self.        Yjfimageview.image = LoadImage (@ "5", @ "jpg");                        } break; ... button case 102: {self.        Yjfimageview.image = LoadImage (@ "6", @ "jpg");                        } break; ... button case 103: {self.        Yjfimageview.image = LoadImage (@ "4", @ "jpg");                    } break;    Default:break; }}-(void) createview{self.    Yjfimageview = [[Uiimageview alloc] Initwithframe:cgrectmake (10, 52, 320-20, 568-64-75)]; Self.    Yjfimageview.image = LoadImage (@ "8", @ "jpg"); Self. Yjfimageview.userinteractionenabled = YES; [Self.view Addsubview:_yjfimageview];}    -(void) didreceivememorywarning{[Super didreceivememorywarning]; Dispose of any resources the can be recreated.} @end

The program executes the console output results such as the following:

Before clicking on the button:

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvewpmmtizntq2/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/southeast ">

This combination of code implementation of the log can be seen

<pre name= "code" class= "OBJC" >didclickbutton and the parameters of the setter method passed in the property are an address, then

, in the blockview.m file
<pre name= "code" class= "OBJC" >buttonactionblock: A copy of Didclickbutton is copied to the stack area, assigned to the instance variable _buttonactionblock

After clicking the button:

Combined with the code implementation of the log can see the entire block of the operation process, but also can be interrupted to view the operation of the block









Copyright notice: This article Bo Master original article. Blog, not reproduced without consent.

iOS to implement block description

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.