For most people, how is the block implemented internally? We can use clang to compile it into C ++ code, and we can see what block is,
Let's look at this problem first,
Int age = 10; void (^ block) () = ^ {nslog (@ "% d", age) ;}; age = 30; block (); // 10
And the following code
_ Block int age = 10; void (^ block) () = ^ {nslog (@ "% d", age) ;}; age = 30; block (); // 30
You will find that these two results are different,
The first output is 10, and the second output is 30.
I want to know what I have done here! We need to compile it into C ++ code to see what is going on in it?
Use the terminal to go to The mian. M file and compile the following code clang-rewrite-objc main. m to generate the main. cpp file.
At this time, we can open mian. cpp and find it in the bottom main function of the file.
Int main (INT argc, const char * argv [])
{
/* @ Autoreleasepool */{_ atautoreleasepool _ autoreleasepool; _ attribute _ (_ blocks _ (byref ))) _ block_byref_age_0 age = {(void *) 0, (_ block_byref_age_0 *) & age, 0, sizeof (_ block_byref_age_0), 10}; void (* block )() = (void (*) () & __ main_block_impl_0 (void *) _ main_block_func_0, & __success, (_ block_byref_age_0 *) & age, 570425344); (age. _ forwarding-> Age) = 30; (void (*) (_ block_impl *) block)-> funcptr) (_ block_impl *) block);} return 0;
}
The block calls a function in the struct:
Static structMain_block_desc_0 {
Size_t reserved;
Size_t block_size;
Void (Copy) (struct _ main_block_impl_0, StructMain_block_impl_0);
Void (Dispose) (struct _ main_block_impl_0 *);
}
After analyzing the C ++ file, we know that
Block is actually a pointer to a struct.
The compiler will generate the corresponding function for the internal code of the block.
In mian. m, when a common int variable is called, The transmitted age is actually a value transfer, while the _ block is a reference transfer!
Therefore, it is the above result!
This is a basic understanding of block. In the next blog, I will introduce the differences between using block in MRC and arc.
Hope to be useful to readers!