1. Functional Requirements
There is a button and a label in the first page. The label displays "Haha" by default. Click the button to enter the second page. On the second page, there is a UITextField and a button2. Click button2 to return to the first page, but at the same time, the text displayed on the label of the first page is modified to the text that was just written in the UITextField.
2. Define the block first
Define the method containing block parameters on the page to pass the value, that is, define it in the .h file of the second page:
Redefine:typedef void (^ReturnTextBlock)(NSString *showText);
//Redefine the block class name void return value type ReturnTextBlock class name (rename class name) NSString *showText parameter
Declare ablockvariable:@property (nonatomic, copy) ReturnTextBlock returnTextBlock;
//Note: The copy attribute is required here, because the block is placed on the stack at the beginning and will only be placed on the heap after copying.
blockCall method:- (void)returnText:(ReturnTextBlock)block;
Implemented in .m file
blockThe call method implementation code:- (void)returnText:(ReturnTextBlock)block { = block; }
At this point, the block preparation work has been completed.
3. Pass the value between two pages through block
On the first page, click the button button to jump to the second page and call the block method of the second page.
-(void)FirstBtnPressed { //Use blockSelf to modify it to avoid the inside of the block block_label being referenced circularly __weak ViewController *blockSelf = self; ShowViewController *orderVC=[[ShowViewController alloc]init]; //block return value (it is quite similar to the proxy writing method, but the syntax is different. For proxy, it is =self;) [orderVC returnText:^(NSString *showText) { =showText; }]; [ self presentViewController:orderVC animated: YES completion:nil]; }
Method of implementing button2 in the second page.m file
-(void)SecondBtnPressed { //As long as __block is added in front of the variable, the value of the variable can be modified in the block. Of course, there are other methods such as adding static. [self dismissViewControllerAnimated:YES completion:^{ //Before using block, you need to make a blank judgment on the block pointer. //Use it directly without null counting, and it will directly crash once the pointer is empty. if ( != nil) { (); NSLog(@"text==%@",); } }]; }
In this way, we can realize the functions we want to implement, which is very simple.
summary
Whoever wants to pass the value defines a method containing the block parameters. Call blcok inside the method and the parameters to be passed are given to blcok. blcok jumps into the 'place' where it wants to execute the code. Passing the value is completed
Summarize
The above is the entire content of this article. I hope the content of this article will be of some help to your study or work. If you have any questions, you can leave a message to communicate.