Experience-let you understand block
In fact, I don't think block users often use block. block users should be unfamiliar. Now let's open the true face of block and look at the essence of block.
For a common local variable, the block only references its initial value (the moment when the block is defined) and cannot track its changes.
Void test () {int age = 10; void (^ block) () = ^ {// common local variable, the block only references its initial value (the moment when the block is defined), and does not track its changes to NSLog (@ "---- age = % d", age) ;}; age = 20; block ();}
The result here is 10. In fact, during compilation, it is equivalent to the following:
Void test2 () {int age = 10; void (^ block) () = ^ {// common local variable, the block only references its initial value (the moment when the block is defined), and does not track its changes to NSLog (@ "---- age = % d", 10) ;}; age = 20; block ();}
The value here is dead. So no matter how much age you change, block doesn't care. In other words, the age here is a local variable, and it will die when it comes to braces. Therefore, it is safer to take the 10 variable directly.
Let's take a look at the variables referenced by the block:
The block can always reference variables modified by _ block.
Void test3 () {_ block int age = 10; void (^ block )() =^{ // The NSLog variable modified by _ block can be always referenced in the block (@ "---- age = % d", age) ;}; age = 20; block ();}
Here: the block can always listen for changes in the value of this age (whether it is a local variable or a global variable), so the output here is that age is 20
The variable modified by _ block can save the life of the variable.
Here, we can see that the variable modified by static is a static variable, and the static variable is always in the memory, so the block sees that the variable modified by static is always in the memory, the block can get this variable every time, so the value of your age changes. The block can be obtained, so this is a dynamic access, instead of taking 10 directly.
Void test4 () {static int age = 10; void (^ block )() =={ // The variable NSLog (@ "---- age = % d", age) modified by static can be always referenced in the block; }; age = 20; block ();}
Int num = 10; void test5 () {void (^ block) () = ^ {// The global variable NSLog (@ "---- num = % d ", num) ;}; num = 20; block ();}
The printed num is 20. Why?
Because the num here is a global variable, since it is a global variable, it is always in the memory, and the block can change with the new value in real time.
To sum up, we only need to determine whether the variable is destroyed immediately. But pay attention to the variable modified by _ block.