"Objective-c Study record" Seventh day

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.