To be honest, I've learned how to use block to do some method callbacks, pass parameters, and simply encapsulate a third-party network library (afnetworking) with block. Although the application of Block is not very handy, but it is extremely like to use this design pattern, and in the project is also widely used.
However, a recent interview of the Learning brother asked me, what is Block it? I am a circle, but after all, I am a senior, I pretended to calmly ask: "What do you understand the Block is?" "It's a block of code that can be used anywhere, and it can pass data," says the brother. My heart Anxi, this child is still a pattern, so Earnest said: Block's essence is can intercept automatic variable anonymous function. But say this sentence I regret, this sentence he meow in the end what is a meaning? Looking at the learning brother satisfied to go, I went crazy to check the information on the Internet, in case the next time the bear children to dig up can not destroy my wise Shenwu image, but there is no very satisfied with the answer, mostly according to the document Description block definition and basic usage, otherwise it is advanced to discuss the implementation mechanism of block bottom , obviously these are not suitable for a beginner can learn to use and can not be confused.
This article is mainly about the use of block callbacks, and how the block is implemented in two parts of this magical callback.
Block Callback Implementation
Don't worry, follow me first. To achieve the simplest use of Block callback parameters, if you can extrapolate, basically can meet the development requirements of OC. Already implemented classmates can jump to the next section.
Let's start by explaining what we're going to do with our example (in fact, the most iconic example of Rotten Street):
There are two view controllers A and B, now click on the button on a to jump to view B, and in B in the TextField input string, click on the Jump button in B to jump back to A, and the previously entered string
appears on the label in A. This means that the data in the B view needs to be recalled in A view.
Students who do not understand can take a look at the final realization:
Block example
There is no longer a description of the Block syntax, students who do not know can point the portal.
First, we need to define two attempts to control Aviewcontroller and Bviewcontroller, and now we need to think about where the Block should be defined.
We can simply think that the callback data is a view, then the Block should be defined in B to get the incoming callback data.
So we define the following in BViewController.h:
//bviewcontroller.h #import <uikit/uikit.h>typedef Span class= "Hljs-keyword" >void (^callbackblcok) (nsstring *text); 1 @interface bviewcontroller: Span class= "Hljs-title" >uiviewcontroller @property ( Nonatomic,copy) Callbackblcok Callbackblock; //2 @end
Here, Code 1 defines void(^) (NSString *text) the alias as a typedef CallBackBlcok . This allows us to define a Block-type variable in code 2 using this alias callBackBlock .
After the definition callBackBlock , we can add the parameters in the Click event in B callBackBlock :
//BViewController.m- (IBAction)click:(id)sender { self.callBackBlock(_textField.text); //1 [self.navigationController popToRootViewControllerAnimated:YES];}
This allows us to call block in the view of a, where we want to get the data callback:
// AViewController.m- (IBAction)push:(id)sender { BViewController *bVC = [self.storyboard instantiateViewControllerWithIdentifier:@"BViewController"]; bVC.callBackBlock = ^(NSString *text){ // 1 NSLog(@"text is %@",text); self.label.text = text; }; [self.navigationController pushViewController:bVC animated:YES];}
In code 1, by passing the data in B to the code block on the callback and assigning A value to A
The entire callback process is implemented by the label in the
The previous example is by assigning blocks directly to the Block property, or by passing block chunks as method parameters.
Due to the difficulty of considering the small partner FQ, the complete sample code is placed on Git.oschina.net, code address: Blockmagic.
The doubts about Block
So far, everything looks pretty good (if you follow the example above), it works fine, and a view also gets the data. But some people may have to say, your code is a problem, you have a problem with your ideas, you are fraught.
Yes, the code does have a problem, and the first question is the problem of circular referencing, in block code blocks in A view:
bVC.callBackBlock = ^(NSString *text){ NSLog(@"text is %@",text); self.label.text = text; };
Code self.label.text = text; , which refers to self in Block, a, and a creates and references B, and B refers callBackBlock to a circular reference, and the compiler does not report any errors, we need to be very careful with this question (interview hundred ask me to talk nonsense? )。 At this point our usual workaround is to use a weak reference to dismiss the loop:
__weak AViewController *weakSelf = self; bVC.callBackBlock = ^(NSString *text){ NSLog(@"text is %@",text); // self.label.text = text; weakSelf.label.text = text; };
The second problem is that my own understanding of the block is not in place, and we all know that block can intercept the automatic variable and that it cannot be modified in block blocks (except with __block modifiers), but weakSelf.label.text the apparent value is modified and no __block modifier is used. Because label it is a global variable, and if a local variable like the following a cannot be modified, the compiler will error:
Local variables
The two problems found through this small example are worth it.
Why does Block implement a magical callback
I'm not going to say here what the principle of implementation is, just the individual's understanding of the magic callbacks that Block can achieve, and where there are errors, please point out.
In the previous use of Block, although it will be used, but there is always a doubt, simply speaking:
Why does block block in A have the ability to invoke data in B?
Looking back at the code we implemented in B, we define a block variable and pass in the parameter at the appropriate time, so why is the self.callBackBlock(_textField.text) value magically passed to block a in a when it is called?
By tidying up the use of the process, I found that our thinking is in the wrong (perhaps I personally), we think that in B _textField.text after the parameters, a block block can get the value. While the idea is true, it is incomplete, and the data that leads us to the callback is the illusion of passing through some sort of underlying implementation, which makes us think that this does not need to be delved into.
The fact is that with a simple collation we can see that the complete callback process should look like this:
Callback Process
- Block code blocks are assigned
bVC.callBackBlock , and callBackBlock the pointer points to this block of code at this point.
- Call
callBackBlock(NSString *text)
-
Because callBackBlock the pointer is to block code blocks in a, the code that executes the code block implements the callback.
Obviously I ignored the code block assignment to callBackBlock this operation (shame).
This principle can now be understood more clearly through a piece of code:
bVC.callBackBlock = ^(NSString *text){ //1 NSLog(@"text is %@",text); }; bVC.callBackBlock = ^(NSString *text){ //2 NSLog(@"text b is %@",text); };
In the above code, we have callBackBlock made two assignments, what will the result be?
Block
As you can see, the block's callback takes effect only for code 2, because callBackBlock the pointer ends up pointing to the code block of code 2. So there is no magical magic, there is no hidden underlying mechanism (this refers to the bottom of the easy-to-understand) so that you can use it with doubts.
Summarize
My personal learning method, summed up is to see the new technology, first run in their own code, can run through, and the use of no difficulty, the basic will not go deep into the (if you encounter a bear child on the pit). But self-reflection, such a learning method is very wrong, write code can not be superficial understanding, if you want to make a breakthrough, do not want to be limited to code farmers, we must thoroughly explore the implementation of the mechanism, at least to ensure that not with doubts to use.
IOS Easy-to-understand Block callback usage and parsing