1 Preface
I have also introduced GCD before, but I feel that it is not deep enough. Today I want to re-understand this concept. GCD is the Grand Central Dispatch) o ). One of its important concepts is queue. The system provides many predefined queues, including the queues that ensure that they are always executed on the Chairman's achievements.
2. Details
GCD strictly follows the FIFO principle. The operation to add to the GCD queue is always started in the order of adding to the queue. Even so, they will not always complete in the same order, because if possible, The GCD queue will automatically allocate its work among multiple threads.
We can understand GCD as a thread pool.
Related to GCD is a language function that becomes a program block, which is a new syntax added to the C language itself. This is very important for making full use of GCD. The idea behind a program block is to treat a specific code block like any other C language type. A program block can be assigned to a variable and passed to a function or method as a parameter. Of course, it can also be executed. In this way, the block can be used as the delegate mode in Objective-C or the replacement path of the callback function in C.
The block is very similar to a method or function. The block can accept one or more parameters and specify a return value. To declare block variables, you can use the "^" symbol and other Code placed in parentheses to declare parameters and return types. To define the block itself, the operations are basically the same, but the actual code for defining the block will be added later, including in curly brackets. Example:
// Declare a block variable with no parameters or returned values called loggerBlock
Void (^ loggerBlock) (void );
// Instantiate this block
LoggerBlock = ^ {NSLog (@ "I'm just gglad they didn't call it a bug ");};
// Execute this block, just like calling a function.
LoggerBlock ();
If you want to modify the external variables in the block, you must add the storage modifier _ block before declaring the variables to read/write the external variables ". Note that there are two underscores in front of the block, not one.
// Define a changeable Block Variable
_ Block int a = 0;
// Define a variable for quick Modification
Void (^ sillyBlock) (void) = ^ {a = 47 ;};
// Check the variable before calling the block
NSLog (@ "a = % d", a); // outputs "a = 0"
// Execution block
SillyBlock ();
// Check the value of a after the call
NSLog (@ "a = % d", a); // outputs "a = 47"
3 conclusion
The above is all content and I hope it will help you.