13: block usage (as attribute, return value, and parameter), block Return Value
Block is easy to use in actual development. It is mainly used for callback and value transfer between controllers. Then classify its usage
Directly run the Code: (all the values with no parameters and no return values)
The first method is to assign values and call values (as attributes) in the currently used folder.
1ZWPerson. h file:2 3 # import <Foundation/Foundation. h> 4 @ interface ZWPerson: NSObject 5 @ property (strong, nonatomic) void (^ play) (); 6 @ end 7 8In the ViewController. m file:9 # import "ViewController. h "10 # import" ZWPerson. h "11 @ interface ViewController () 12 @ property (strong, nonatomic) ZWPerson * p; 13 @ end14 @ implementation ViewController15 16-(void) viewDidLoad {17 [super viewDidLoad]; 18 ZWPerson * p = [[ZWPerson alloc] init]; 19 p. play = ^ () {20 NSLog (@ ""); 21}; 22 _ p = p; 23} 24 25-(void) touchesBegan :( NSSet <UITouch *> *) touches withEvent :( UIEvent *) event26 {27 // you can directly call this method 28_p if needed in the current folder. play (); 29} 30 @ end
The second method of use (as a method parameter) is mainly called by the outside world. It can only be called within the method and is used for callback and value transfer.
You can also define a method call in the current folder.
1ZWPerson. h file:2 3 # import <Foundation/Foundation. h> 4 @ interface ZWPerson: NSObject 5 6-(void) eat :( void (^) () bolck; 7 8 @ end 9 10In the ZWPerson. m file:11 # import "ZWPerson. h "12 @ implementation ZWPerson13-(void) eat :( void (^) () block14 {15 NSLog (@" delicious "); 16 block (); 17} 18 @ end19 20In the ViewController. m file:21 # import "ViewController. h "22 # import" ZWPerson. h "23 @ interface ViewController () 24 @ property (strong, nonatomic) ZWPerson * p; 25 26 @ end27 @ implementation ViewController28 29-(void) viewDidLoad {30 [super viewDidLoad]; 31 32 ZWPerson * p = [[ZWPerson alloc] init]; 33 [p eat: ^ {34 NSLog (@ "sleeping"); 35}]; 36} 37 @ end
The third method (as the return value of the method) cannot be called internally, but can only be called externally. It is equivalent to replacing the method!
1ZWPerson. h file:2 # import <Foundation/Foundation. h> 3 @ interface ZWPerson: NSObject 4-(void (^) () run; 5 @ end 6 7In the ZWPerson. m file:8 # import "ZWPerson. h "9 @ implementation ZWPerson10-(void (^) () run11 {12 return ^ () {13 NSLog (@" 3 km running "); 14 }; 15} 16 @ end17 18In the ViewController. m file:19 # import "ZWPerson. h "20 @ implementation ZWPerson21-(void) viewDidLoad {22 [super viewDidLoad]; 23 ZWPerson * p = [[ZWPerson alloc] init]; 24 // run can be called directly through the dot syntax. If there is a parameter, () indicates that the parameter can be passed, 25 p. run (); 26}