Block usage in iOS development and iosblock usage
Source code download
Block usage
He used block for convenience, and many people were confused. Here I wrote a Demo to explain how to use block.
Many people think that the block is used to pass values on the previous interface. In fact, it is more specifically used to pass values between interfaces, in fact, you only need to pass the value between the view, between the controller, or between the view and the controller, you can use a block. When the value is less, it is more convenient to use a block than to use a proxy.
After a block is created, it is stored in the stack. copy is required for the semantic features of the block. You can use copy to place the block from the stack to ensure that the block exists every time you use it, therefore, we often need to define attributes when using them to save the block variables.
The following is an example.
First, create two types of BlockViewController and BlockView in the project.
BlockView only creates several buttons. Using BlockViewController can reduce the amount of code tasks of BlockViewController. However, BlockView only has one instance variable, which is defined in the extension, external access is unavailable. When we add a trigger event for the button, we need to obtain the tag value of the button. In this case, we need to obtain the tag of the clicked button to add a response event for different buttons.
Define a block variable and a method in BlockView. h. The parameters of the method are block-type.
# Import <UIKit/UIKit. h> // Step 1: declare blocktypedef void (^ ButtonActionBlock) (NSInteger tag); @ interface BlockView: UIView-(void) buttonActionBlock :( ButtonActionBlock) didClickButton; @ end
In BlockView. m
<Pre name = "code" class = "objc"> # import "BlockView. h "@ interface BlockView () // Block // The block is stored in the stack zone after it is created. copy is required for the semantic features of the block, copy can be used to place the block from the stack area to the heap area to ensure that @ property (nonatomic, copy) ButtonActionBlock buttonActionBlock exists in the block every time you use the block; @ property (nonatomic, strong) UIButton * button; @ end @ implementation BlockView-(id) initWithFrame :( CGRect) frame {self = [super initWithFrame: frame]; if (self) {CGFloat x = 5; CGFl Oat 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 + 10), y, width, height); self. button. tag = 100 + I; self. button. backgroundColor = [UIColor cyanColor]; self. button. layer. cornerRadius = 5; self. button. layer. masksToBounds = YES; [self. button setTit Le: [NSString stringWithFormat: @ "% d", I] forState: UIControlStateNormal]; [self. button addTarget: self action: @ selector (handleButton :) forControlEvents: UIControlEventTouchUpInside]; [self addSubview: _ button] ;}} return self ;}// process button click events, callback block-(void) handleButton :( UIButton *) button {NSLog (@ "3"); NSInteger tag = button. tag; // Step 2: Return block self. buttonActionBlock (tag), NSLog (@ "6"); NSLo G (@ "7");} // self. buttonActionBlock = didClickButton; after execution, the setter method of the buttonActionBlock attribute is called, and the block Variable didClickButton is passed to the parameter-(void) buttonActionBlock :( ButtonActionBlock) of the setter method) didClickButton {NSLog (@ "1"); NSLog (@ "----------- didClickButton = % p", didClickButton); self. buttonActionBlock = didClickButton;} // rewrite the setter method of the buttonActionBlock attribute. Here, the setter method is rewritten to show that the method is to copy the passed block Variable in depth and copy it to the heap, and assigned the instance variable buttonActionB. Lock, so that we can use the block Variable at any time (after the block is created in the stack area, the method is recycled and cannot be used again)-(void) setButtonActionBlock :( ButtonActionBlock) buttonActionBlock {NSLog (@ "2"); if (_ buttonActionBlock! = ButtonActionBlock) {NSLog (@ "++ buttonActionBlock = % p", buttonActionBlock); _ buttonActionBlock = [buttonActionBlock copy];} @ end
Import BlockView. H files to the BlockViewController. m file.
Code implementation in the BlockViewController. m file
# Import "BlockViewController. h "# import" BlockView. h "// obtain the 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;}-(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 call its method buttonActionBlock: // step 3, call block [blockView buttonActionBlock: ^ (NSInteger tag) {// The implementation of block NSLog (@ "4"); [self handleButton: tag]; NSLog (@ "5") ;}]; [self createView];} // process the Click Event of the custom 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 didreceivemorywarning]; // Dispose of any resources that can be recreated .} @ end
The output result on the console is as follows:
Before clicking the button:
From this, we can see from the logs recorded in the code implementation.
<Pre name = "code" class = "objc"> the parameter of didClickButton and the setter method of the incoming attribute is an address
, BlockView. m file
<Pre name = "code" class = "objc"> buttonActionBlock: copy the didClickButton to the stack area in the method and assign it to the instance variable _ buttonActionBlock.
Click the button:
The execution process of the entire Block can be seen through the log played in the code implementation, or the execution process of the Block can be viewed through interruption.
Block reference in iOS development
ViewController has an addChild method. Just add the view.
What is block for IOS development? How to declare a block? Examples
A block is a code block, such as some "anonymous functions" in other Web programming languages ". In objc, block is usually used to implement the proxy method, that is, callback. To use a proxy, you need to set the data receiver of the proxy, and the proxy method is separated for processing. The block can put the separated code into a code block.
/// //. H
Typedef void (^ MyBlock) (int value );
@ Property (nonatomic, weak) MyBlock block;
-(Void) setMyBlock :( void (^) (int value) block;
/// //. M
-(Void) setMyBlock :( void (^) (int value) block {
If (block ){
Self. block = block;
}
}