"Go" iOS deep Learning (Block comprehensive analysis)

Source: Internet
Author: User

Source: http://my.oschina.net/leejan97/blog/268536

This article is translated from Apple's documentation, there are limitations, but also to add their own understanding of the part.

If there is block syntax do not understand, you can refer to the Fuckingblocksyntax, inside the block

For ease of comparison, the following code I assume is written in the Viewcontroller subclass of the

1, the first part

Define and use block,

-(void) viewdidload{    [Super Viewdidload];    (1) define a block void (^printblock) with no return value (    ) = ^ () {        printf ("no number");    };    Printblock ();          Printblock (9);         int mutiplier = 7;    (3) Define a code block named Myblock, with the return value type int    int (^myblock) (int) = ^ (int num) {        return num*mutiplier;    }    Use the defined myblock    int newmutiplier = Myblock (3);    printf ("Newmutiplier is%d", Myblock (3));} Defined in the-viewdidload method external//(2) defines a parameter that has no return value of Blockvoid (^printnumblock) (int) = ^ (int num) {    printf ("int number is%d", num);};

Defining a block variable is equivalent to defining a function. But the difference is also obvious, because the function must be defined outside the-viewdidload method, and the block variable is defined inside the Viewdidload method. Of course, we can also define blocks outside of the-viewdidload method, such as the definition of code block Printnumblock above, just outside of-viewdidload.

Then take a look at the order of the above code, in terms of (3) Myblock distance, in the definition of the place, and will not execute the code inside the block{}, and after Myblock (3) call to execute the code, which is similar to the understanding of the function, The code in the Block body (inside the function body) is executed only when the block (function) is called. So the simple code example above, I can make the following conclusions,

(1) In a class, define a block variable, just like defining a function;

(2) blocks can be defined within a method or can be defined outside the method;

(3) The code in its {} body is executed only when the block is called;

(PS: For article (2), the block defined outside the method is actually a file-level global variable)

So what's the point of defining a block in a class, specifically defining a block in the-viewdidload method body? I said it would be just a private function. As I said before, block is actually the equivalent of a proxy, so how can I compare it to the proxy analogy to understand it? I can say this at this point: The block in this class is equivalent to the class itself obeying a certain protocol, and then let oneself agent to do something. It's a mouthful, isn't it? Look at the following code,

Define a protocol @protocol viewcontrollerdelegate<nsobject>-(void) Selfdelegatemethod; @end// This class implements this Protocol Viewcontrollerdelegate@interface Viewcontroller () <ViewControllerDelegate> @property (nonatomic, assign) id<viewcontrollerdelegate> delegate; @end

Then the code in-viewdidload is as follows,

-(void) viewdidload{    [Super Viewdidload];    Do any additional setup after loading the view from its nib.    Self.delegate = self;    if (self.delegate && [self.delegate respondstoselector: @selector (Selfdelegatemethod)]) {        [self.delegate Selfdelegatemethod];}    } #pragma mark-viewcontrollerdelegate method//Implement the method in the Protocol-(void) selfdelegatemethod{    NSLog (@ "self-commissioned method of Implementation");}

Do you see the wonderful place for this writing? Instead of delegating other classes to implement a method, you entrust yourself to implement a method. The definition of a block in this class is actually the idle egg ache, entrust oneself to the word to do something, the actual meaning is not big, so you rarely see others code directly in the class to define block then use, block many of the use of blocks are used across two classes, For example, as a property attribute or as a parameter to a method, this can span two classes.

2, the second part

Use of __block Keywords

In the block's {} body, it is not possible to change the outside variables, such as the following statement,

-(void) viewdidload{    //The block is defined inside the method    int x = +;    void (^sumxandyblock) (int) = ^ (int y) {    x = x+y;    printf ("New x value is%d", x);    };    Sumxandyblock (50);}

What's wrong with this code, Xcode will prompt for x variable error message: Variable is not assigning (missing __block type), this time to int x = 100; statement preceded by the __block keyword, as below,

__block int x = 100;

This allows you to modify the external variables in the block's {} body.

3, the third part: block as a property to achieve the value of the page transfer

Requirements: In Viewcontroller, click Button,push to the next page Nextviewcontroller, enter a string of characters in the Nextviewcontroller input box TextField, return the time, Display text content on Viewcontroller label,

(1) The first method: first of all to see through the "Protocol/proxy" is how to achieve the value of two pages between the bar,

Nextviewcontroller is the second page of push entry//nextviewcontroller.h file//Define a protocol, the previous page Viewcontroller to obey the protocol, and implement the method in the Protocol @protocol nextviewcontrollerdelegate <nsobject>-(void) Passtextvalue: (NSString *) Tftext; @end @ Interface Nextviewcontroller:uiviewcontroller@property (nonatomic, assign) id<nextviewcontrollerdelegate> Delegate @end//nextviewcontroller.m File//Click button to return to the previous Viewcontroller page-(ibaction) popbtnclicked: (ID) Sender {    if ( Self.delegate && [self.delegate respondstoselector: @selector (passtextvalue:)]) {        // Self.inputtf is the TextField input box in this page        [self.delegate passTextValue:self.inputTF.text];    }    [Self.navigationcontroller Popviewcontrolleranimated:yes];}

Next we look at the contents of the Viewcontroller file,

VIEWCONTROLLER.M file @interface viewcontroller () <NextViewControllerDelegate> @property (Strong, Nonatomic) Iboutlet UILabel *nextvcinfolabel; @end//Click button to go to the next Nextviewcontroller page-(ibaction) btnclicked: (ID) sender{    nextviewcontroller *NEXTVC = [[ Nextviewcontroller alloc] initwithnibname:@ "Nextviewcontroller" bundle:nil];    Nextvc.delegate = self;//set Agent    [Self.navigationcontroller PUSHVIEWCONTROLLER:NEXTVC animated:yes];}// Implement the method in protocol nextviewcontrollerdelegate #pragma mark-nextviewcontrollerdelegate method-(void) Passtextvalue: (NSString *) tftext{    //self.nextvcinfolabel is a string that displays Nextviewcontroller passed over the label object    self.nextVCInfoLabel.text = Tftext;}

This is the way to pass values between two pages implemented by Protocol/proxy.

(2) The second method: use block as the property, to achieve the value between two pages,

First look at the contents of the Nextviewcontroller file,

NextViewController.h file @interface nextviewcontroller:uiviewcontroller@property (nonatomic, copy) void (^ Nextviewcontrollerblock) (NSString *tftext); @end//nextviewcontorller.m file-(ibaction) popbtnclicked: (ID) Sender {    if (self). Nextviewcontrollerblock) {self        . Nextviewcontrollerblock (Self.inputTF.text);    }    [Self.navigationcontroller Popviewcontrolleranimated:yes];}

And then look at the contents of the Viewcontroller file,

-(Ibaction) btnclicked: (ID) sender{    nextviewcontroller *NEXTVC = [[Nextviewcontroller alloc] initwithnibname:@ " Nextviewcontroller "Bundle:nil";    Nextvc.nextviewcontrollerblock = ^ (NSString *tftext) {        [self resetlabel:tftext];    };    [Self.navigationcontroller PUSHVIEWCONTROLLER:NEXTVC animated:yes];} #pragma mark-nextviewcontrollerblock method-(void) Resetlabel: (NSString *) textstr{    Self.nextVCInfoLabel.text = Textstr;}

All right, so much code, you can use block to achieve the purpose of passing values between two pages, actually replacing the delegate function.

In addition, the code can be downloaded from the blog to GitHub, if because GitHub is a wall, you can use git clone + full link in the terminal to clone the project to local.

GitHub code, you can open two debugging modes, you need to comment on the project configuration file blocksamp-prefix.pch or to comment the following code,

#define Debug_blcokpassvalueenable

You can turn on two kinds of debugging, if you annotate the above statement is to use delegate for debugging, otherwise use block for debugging.

"Go" iOS deep Learning (Block comprehensive analysis)

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.