Main content: Block (Block syntax, Block usage, and Block implement array sorting)
Main content: Block (Block syntax, Block usage, and Block implement array sorting)
I. Block syntax
Block: Block syntax, essentially an anonymous function (a function without a function name), similar to a function pointer
Function review:
Implements the encapsulation of a function code block (three steps: function declaration, function definition, and function call)
Function pointer review:
Function pointer (variable): The pointer variable that stores the function address (function name)
Int (* p) (int x, int y) = sum
Function pointer type: int (*) (int x, int y), that is, pointer to two integer parameters, an integer return value function
Function pointer variable: p; function pointer value: sum
Block:
Note:
1. the last ";" must be written.
2. the parameter variable name cannot be omitted.
3. the block value is an anonymous function.
Anonymous function: a function without a name
Block syntax:
Details:
Block type: int (^) int
Block variable: myblock
Block value: ^ (int sum) {return 7 * sum ;};
That is: ^ return value type (parameter list) {function body} (the return value type can be omitted)
II. Block Usage
Example:
Write a Block that returns two integer values and
Int (^ sum) (int, int) = ^ (int x, int y ){
Return x + y;
}
Int a = sum (20, 10); // call the block function
Write a block that calculates the maximum value.
Int (^ maxBlock) (int, int) = ^ (int x, int y ){
Return x> y? X: y;
}
Perform typedef on the block
Typedef int (^ sumBlock) (int x, int y );
New type: sumBlock
Original type: int (^) (int, int)
Equivalent: sumBlock ^ sum2 = ^ (int x, int y ){
Return x + y;
}
3. block and local variables and global variables
External variables can be used inside the block.
For global variables: readable and writable
For local variables: readable and non-writable. if you want to change the value of a local variable, add _ block before the local variable for modification.
Example:
Block and local variables
Block and global variables:
III. Block and array sorting
Example:
Sort Student objects
Student * stu1 = [Student StudentWithName: @ "xiaoming", age: 21];
Student * stu2 = [Student StudentWithName: @ "", age:];
NSMutableArray * mu = [NSMutableArray arrayWithObjects: stu1, stu2, nil];
Mu sortUsingcomparator: ^ NSComparionResult (id obj1, id obj2 ){
If ([obj1 getAge]> [obj2 getAge]) {
Return NSOrderedDescending;
} Else if ([obj1 getAge] <[obj2 getAge]) {
Return NSOrderedAscending;
} Else {
Return NSOrderedSame;
}
}
IV. literal
Literal is a new writing method that can simplify the code to a certain extent.
Note: objects created literally are constructed by variables and are immutable.