How the iOS development-object-c block is implemented

Source: Internet
Author: User

We can use block as a closure function, which can access external variables and local variables, but by default it is not possible to modify external variables. You can use it to do callback methods that are more intuitive than using proxies (Delegate). Incidentally, many of Apple's interfaces (APIs) use block.

First, the basic definition of block

Block's basic notation (also detailed):

ReturnType (^blockname) (params) = ^returntype (params) {    //};

Chinese re-interpretation: return type (^block's name) (block parameter) = ^ return type (block parameter) {put code here}, example:

int (^myblock) (intint num2) = ^int(intint  num2) {    return  (a);

If your block does not require a return type and parameter, you can abbreviate it as:

void (^MYBLOCK2) () = ^(){    };

Or

void (^MYBLOCK2) (void) = ^void(void) {    };

Returns a type or parameter that can be replaced with "void" if not.

You can also delete the equals sign to the right, ^ after (), which is:

void (^MYBLOCK2) () = ^{    };

Isn't that very concise?

You can also define a block function, but do not write the implementation of the function, we can later write the implementation of the specific function, like this:

void (^MYBLOCK2) (void= ^{    };

Second, block as a method definition

To define a block in a method, unlike the above, the block's name does not need to be written on the declaration, but in the back, like this:

-(void) Getwtihblock: (void (^) ()) block{    //  code ...         // Remember to call block     block ();}

How to use:

[Self getwtihblock:^{    NSLog (@ "sdf");}];

Here is an example of a detailed point, and write a note:

/** * append self string n times (add a newline before each copy \ n) * * @param string String * @param count append * @param stringblock target block, where s The TR parameter is the result string*/ //Blocks can also be defined in the method, but do not need to define the block's name//iOS develops a lot of APIs that also use blocks, like UIView's block animations- (void) Getstrwithstring: (NSString *)stringCopycount: (int) Count resultstring: (void(^) (NSString *str)) stringblock{nsmutablestring*newstring = [nsmutablestring stringwithstring:string];  for(Nsuinteger i =0; I < count; i++) {Nsuinteger len= [stringlength]; NSString*insertstring = [NSString stringWithFormat:@"\n%@",string];    [NewString insertstring:insertstring Atindex:len]; }    //call block, pass in the string newstringStringblock (newstring);}

Usage is the same:

Blockobject *block = [[Blockobject alloc] init];[ Block getstrwithstring:@ "Garvey"              copycount:3            Resultstring:^ (NSString *str) {               //  str for processed results               NSLog (@ " Str is%@ " , str);           }];

Sometimes the complex block syntax makes the declaration of a function difficult to read, so a typedef is often used to make a new type of block.

void (^resultblock) (NSString *str);

When you define a method, you become:

-(void) GetStrWithString2: (NSString *) string                copycount: (int) Count             resultstring: (Resultblock) Stringblock; 

Let's compare the use of typedef before and after:

// use before -(void) getstrwithstring: (NSString *)string               copycount: (int ) Count            resultstring: (void (^) (NSString *str)) Stringblock; // after use -(void) GetStrWithString2: (NSString *)string                copycount: ( int ) Count             resultstring: (resultblock) Stringblock;

Note: The use method is the same, but the definition becomes simple.

If you have been using proxy (Delegate) for method callbacks, you can now try to use the block function.

Blog Garveycalvin

Blog Source: http://www.cnblogs.com/GarveyCalvin/

This article copyright belongs to the author and the blog Garden altogether, welcome reprint, but must retain this paragraph statement, and gives the original link, thanks cooperation!

How the iOS development-object-c block is implemented

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.