code block
In addition to the code in the function, the code block also includes variable bindings. The code block also has another name: Closure (closure).
Code blocks protect two types of bindings: automatic and managed. Automatic binding uses memory in the stack, and managed bindings use the memory in the heap.
The format of the code block is somewhat like the function pointer. function pointer: void (*F) (void), block of code: void (^f) (void), simply replace "*" with "^".
Then we'll write a block of code:
Int (^f) (int a,int b) = ^ (int a,int b) {return (a+b);};
int res = f (n);
printf ("Res is%d\n", res);
This is done by code blocks to calculate the sum of two numbers. The syntax is summarized as follows:
<returnType> (^blockname) (list of arguments) = ^ (arguments) {body;};
< return type > (^ code block name) (parameter list) = ^ (parameter) {code body;};
Note: The compiler can infer the return type of a code block, so it can be omitted, and parameters can be omitted when the code block has no parameters. The following (print "Hello IOS"):
void (^hello) () = ^{printf ("Hello ios\n");};
Use code blocks without writing "^", you need to add the definition, such as: int res = f, as in the function. If you use code blocks directly, you do not need to create a code block variable to directly relate the content, and here is a function of sorting the array:
Nsarray *array = [Nsarray arraywithobjects:@ "A", @ "C", @ "E", @ "D", @ "B", nil];
Nsarray *res = [Array sortedarrayusingcomparator:^ (NSString *obj1,nsstring *obj2)]{
return [Obj1 compare:obj2];}];
It looks like a function definition in javascript:)
"Objective-c Study record" Seventh day