1:可以捕获不可以修改变量
局部变量
2:可以捕获且可以修改变量
全局变量
静态变量
__block修饰的局部变量
下面我们看个例子,大家根据例子输出结果来思考加深理解。
.h
#import <UIKit/UIKit.h>
@interface Person : NSObject
@property (nonatomic, copy) NSString *name;
@end
typedef void(^PersonBlock)(Person *);
@interface ViewController : UIViewController
@property (nonatomic, copy) PersonBlock myBlcok;
@end
.m
#import "ViewController.h"
@implementation Person
@end
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self testBlock];
}
-(void)testBlock{
Person *p1 = [[Person alloc]init];
p1.name = @"p1";
Person *p2 = [[Person alloc]init];
p2.name = @"p2";
Person *p3 = [[Person alloc]init];
p3.name = @"p3";
NSArray *arr = @[p1,p2,p3];
for (Person *p in arr) {
int i=2;
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"没传参数时%@",p.name);
NSLog(@"%d",i);
});
i=4;
_myBlcok = ^(Person *p){
NSLog(@"传递参数时%@",p.name);
};
_myBlcok(p);
p.name = @"p-new";
}
void (^Block)(int) = ^(int i){
NSLog(@"值是%d",i*2);
};
int a = 4;
Block(a);
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"主线程调用最后值是%d",a*2);
});
a = 6;
}
@end
结果:
2019-04-11 15:51:11.475200+0800 Block[63860:3183459] 传递参数时p1
2019-04-11 15:51:11.475373+0800 Block[63860:3183459] 传递参数时p2
2019-04-11 15:51:11.475499+0800 Block[63860:3183459] 传递参数时p3
2019-04-11 15:51:11.475609+0800 Block[63860:3183459] 值是8
2019-04-11 15:51:11.481302+0800 Block[63860:3183459] 没传参数时p-new
2019-04-11 15:51:11.481674+0800 Block[63860:3183459] 2
2019-04-11 15:51:11.481816+0800 Block[63860:3183459] 没传参数时p-new
2019-04-11 15:51:11.481919+0800 Block[63860:3183459] 2
2019-04-11 15:51:11.482052+0800 Block[63860:3183459] 没传参数时p-new
2019-04-11 15:51:11.482152+0800 Block[63860:3183459] 2
2019-04-11 15:51:11.482262+0800 Block[63860:3183459] 主线程调用最后值是8
网友评论