The Block for iOS development

Source: Internet
Author: User

iOS development Block1. What is the role of Block,block

UI Development and network common function implementation callback, button event handling method is callback method, network hit callback processing

(1) button target-action a method in the incoming button

(2) Table View Pass in a pointer to self, callback view controller heavy method

(3) Block statement blocks, resolve callbacks, understood as "anonymous functions", this function is defined in the method

Basic use of 2.block (syntax)

Defining a block variable

Defining block statement Blocks

//Block understands anonymous functions//void func ()//{    //}        //definition of 1.block variables//tip: Grammar poses problems with men's shoes//void func (); //defines the block variable, ^ indicates that the block is defined//Tip: The function name is left and right in parentheses, preceded by the name ^    void(^block)        (); //define block statement blocks, stored in block variablesblock = ^void() {NSLog (@"I am Block");        }; //ExecutionBlock ();

Block parameters and return values

 //2. With parameters and return values block//example implementation calculates two number of blocks//int Myadd (int x, int y);        int(^myadd) (intXintY) = ^int(intXinty) {returnx+y;    }; ints = Myadd (Ten, -); NSLog (@"s =%d", s);

Block captures external variables

Precautions for Block

@interfaceViewcontroller () {int_page;} @property (copy,nonatomic) NSString*URL;@end //3.block is the capture of external variables//Considerations for block using variables outside of block        intnum =Ten; __blockintval = -; void(^BBBB) () = ^void()    {        //ability to use and modify instance variables_page =1; //You cannot modify the value of a local variable in a block, but you can use the//num++; //can modify local variables of __block modification in blockval++; //there may be warnings due to memory problems, note//__weak typeof (self) weakself = self;//Weakself.url = @ "text";Self.url =@"text";    }; BBBB ();
3.block application in development (OC,UI, network)

1.NSMutableArray sorting

2.UIView Animation

3.block Implement Interface Reverse value

-(void) blockdelelopapply{//Applications in OC//1.NSMutableArray SortingDog*ahua =[[Dog alloc]init]; Ahua.nikename=@"Ahua"; Ahua.age=4; Dog*amiao =[[Dog alloc]init]; Amiao.nikename=@"Amiao"; Amiao.age=3; Dog*dahuang =[[Dog alloc]init]; Dahuang.nikename=@"Dahuang"; Dahuang.age=5; Nsmutablearray*marr =[[Nsmutablearray Alloc]initwitharray:@[ahua,amiao,dahuang]]; //Marr sortusingselector:<# (SEL) #>[Marr Sortusingcomparator:^nscomparisonresult (IDObj1,IDobj2) {Dog*adog =obj1; Dog*bdog =Obj2;//return adog.age > bdog.age;        return[Adog.nikename Compare:bDog.nikeName] >0;        }];  for(Dog *dinchMarr) {NSLog (@"name =%@,age =%d", D.nikename,d.age); }        //2.UIView AnimationUILabel *label = [[UILabel alloc]initwithframe:cgrectmake (Ten, $, -, -)]; Label.text=@"KKKK"; Label.backgroundcolor=[Uicolor Redcolor];        [Self.view Addsubview:label]; //Move Down//[UIView animatewithduration:<# (Nstimeinterval) #> animations:<#^ (void) animations#>][UIView animatewithduration:2animations:^{CGRect frame=Label.frame; Frame.origin.x+= $; Label.frame=frame; } Completion:^(BOOL finished) {NSLog (@"Finish"); [UIView animatewithduration:1animations:^{label.transform=cgaffinetransformmakerotation (M_PI); } Completion:^(BOOL finished) {[UIView animatewithduration:2animations:^{label.frame= CGRectMake (Ten, $, -, -); Label.transform=cgaffinetransformmakerotation (M_PI);                    }];    }];        }]; //3.block Implement Interface reverse valueUIButton*button =[UIButton Buttonwithtype:uibuttontypesystem]; Button.frame= CGRectMake (0, -, the,Ten); [Button Settitle:@" Change"Forstate:uicontrolstatenormal];    [Button addtarget:self action: @selector (buttonact:) forcontrolevents:uicontroleventtouchupinside];    [Self.view Addsubview:button]; }-(void) Buttonact: (UIButton *) but{Secondviewcontroller*svc =[[Secondviewcontroller alloc]init]; //Set Block[Svc setchangebackgroundcolor:^ (NSString *color) {        if([Color isequaltostring:@"Blue"]) {Self.view.backgroundColor=[Uicolor Bluecolor];                }    }]; [Self presentviewcontroller:svc animated:yes completion:nil];}

Reverse Pass Value:

Using block to implement the interface transfer value

If there are two interface a interface, B interface, a interface to create a B interface, B boundary value passed to a interface

a interface settings block, B interface Save block

A. Defining a block in the second interface

// in order to pass a block-(voidvoid (^) (NSString *color)) Action to the second interface; // @property (nonatomic,copy) setchangebackgroundcolor (void (^__) (NSString *__color));

B. The second interface implements a block

@interface Secondviewcontroller () {    /// defines the block variable in order to save the passed-in parameter    void (^_action) ( NSString *color);} @end @implementation Secondviewcontroller-(void) Setchangebackgroundcolor: (void (^) (NSString *)) action{    = Action;}

C. The second interface assigns a value to the block

// Change the color    of the interface if (_action) {        _action (@ "blue");    }

D. First interface setting block

Secondviewcontroller *svc = [[Secondviewcontroller alloc]init];

// Set block    [Svc setchangebackgroundcolor:^ (NSString *color) {        if ([color isequaltostring:@ "  Blue"]) {            = [Uicolor bluecolor];        }    }];

[self presentviewcontroller: Svc animated:YES completion:nil];

Code download

The Block for iOS development

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.