标签:
一、声明和定义
1、声明
声明方式:返回值(^block)(参数)。声明时,参数变量名可以省略;使用时,参数变量名不能省略,不然会无法调用传入的参数
void(^block)(); void(^block)(int); int(^block)(int);
2、定义
void(^block)() = ^{};
void(^block)() = ^(){};
void(^block)(int) = ^(int a){};
int(^block)(int) = ^int(int a){}; int(^block)(int) = ^(int a){};
二、简单使用场景
保存一段代码,在不同方法中调用
@interface ViewController () @property (nonatomic, strong) void(^block)(); @end - (void)viewDidLoad { [super viewDidLoad]; void(^block)() = ^{ NSLog(@"调用Block"); }; _block = block; } - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{ _block(); }
使用技巧:
inlineBlock:快速生成block代码
<#returnType#>(^<#blockName#>)(<#parameterTypes#>) = ^(<#parameters#>) { <#statements#> };
三、逆向传值
在数据来源的第二个文件中,定义一个block变量,放入需要传递的值
#import <UIKit/UIKit.h> @class modalViewController; @interface modalViewController : UIViewController @property(nonatomic,strong)void (^valueBolck)(NSString *value); @end -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{ if (_valueBolck) { _valueBolck(@"123"); } [self dismissViewControllerAnimated:YES completion:nil]; }
在modal回来的需接受数据的文件中,导入数据源文件,并接收值
#import "ViewController.h" #import "modalViewController.h" -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{ modalViewController *mVC = [[modalViewController alloc]init];
mVC.valueBolck = ^(NSString *value){ NSLog(@"%@",value); };
[self presentViewController:mVC animated:YES completion:nil]; }
四、属性
1、MRC下的block
肚子疼,歇会儿再写
标签:
原文地址:http://www.cnblogs.com/xiao-xiao-/p/5136161.html