1. Define and use block
1 #import "ViewController.h"2 3 @interfaceViewcontroller ()4 5 @end6 7 @implementationViewcontroller8 9- (void) Viewdidload {Ten [Super Viewdidload]; One A //define block no return value, no parameter - void(^nameblock) () = ^ () { -NSLog (@"Name: Block"); the }; - - //defines a block with a return value, with parameters - int(^ageblock) (int) = ^(intAge ) { +NSLog (@"Age:%d", age); - returnAge +1; + }; A at //Call Block - Nameblock (); - intAge = Ageblock (3); -NSLog (@""" Age:%d", age); -Nameandageblock (@"SD. Team", -); - } in - void(^nameandageblock) () = ^ (NSString *name,intAge ) { toNSLog (@"Name:%@, Age:%d", name,age); + }; - the- (void) didreceivememorywarning { * [Super didreceivememorywarning]; $ }Panax Notoginseng - @end the +Block Definition and use
Operation Result:
By running the simple code example above, you know:
[1]. In a class, defining a block variable is like defining a function.
[2]. Blocks can be defined inside a method or outside of a method.
[3]. The code in its {} body is executed only when the block is called.
2.__block keywords
In the block {} body, you can not change the outside variables, will be error (Variable is not assigning (missing __block type)), such as the following:
1- (void) Viewdidload {2 [Super Viewdidload];3 intMyAge = -;4 void(^updateage) (int) = ^(intAge ) {5MyAge = MyAge +Age ;6NSLog (@"age:%d", myAge);7 };8}
How do you correct the value on the outside? By adding the __block keyword, you can
1- (void) Viewdidload {2 [Super Viewdidload];3__blockintMyAge = -;4 void(^updateage) (int) = ^(intAge ) {5MyAge = MyAge +Age ;6NSLog (@"age:%d", myAge);7 };8 9Updateage (3);Ten}
3.Block as Property attribute
If there is a need: In the Viewcontroller, click the Settings button, push to the next page Settingviewcontroller, in the Settingviewcontroller Age input Box TextField update ages, At the time of return, the age label on Viewcontroller shows the updated age. Can be achieved through delegate, Delegate said before, this time we will use block to achieve.
Settingviewcontroller:
1 //SettingViewController.h File2 @interfaceSettingviewcontroller:uiviewcontroller3@property (nonatomic, copy)void(^updateageblock) (NSString *Age );4 5 @end6 7 //settingviewcontroller.m File8-(Ibaction) updateagebtnclicked: (ID) Sender {9 if(self.updateageblock) {Ten Self.updateageblock (self.ageTextField.text); One } A [Self.navigationcontroller Popviewcontrolleranimated:yes]; -}
Viewcontroller:
1-(Ibaction) settingclicked: (ID) Sender2 {3Settingviewcontroller *SETTINGVC = [[Settingviewcontroller alloc] Initwithnibname:@"Settingviewcontroller"Bundle:nil];4Settingvc.updateageblock = ^ (NSString *Age ) {5 [self updateagelabel:age];6 };7 [Self.navigationcontroller PUSHVIEWCONTROLLER:SETTINGVC animated:yes];8 }9 Ten- (void) Updateagelabel: (NSString *) Age One { ASelf.ageLabel.text =Age ; -}
We also achieved the delegate effect by block mode.
[Objective-c] 020_ Block