(一)blok简单语法
block 声明 :
int (^myblock)(int a);
block 实现 :
myblock = ^(int a){
a=1+a;
NSLog(@"a=%i",a);
return a;
};
block 调用 :
myblock(1);
(二)block回调:
ViewController.m
blockViewController *blockview = [[blockViewController alloc]init];
blockview.myblock = ^(int a){
a=1+a;
NSLog(@"a=%i",a);
return a;
};
[self.navigationController pushViewController:blockview animated:YES];
blockViewController.h
@property (nonatomic , copy) int (^myblock)(int);
blockViewController.m
self.myblock(1);
打印结果:
2015-10-22 09:33:08.805 block总结[631:22503] a=2
(三)block 使用中注意点
1、block可以访问局部变量,但是不能修改
修改局部变量,在block代码块中声明前加 __block
__block int num = 0;
blockview.myblock = ^(int a){
num = num+1;
a=1+a;
NSLog(@"a=%i",a);
NSLog(@"num=%i",num);
return a;
};
打印结果:
2015-10-22 09:59:48.518 block总结[677:33725] a=2
2015-10-22 09:59:48.519 block总结[677:33725] num=1
2、防止在 block内使用self导致循环 引用
__weak typeof (self) weakSelf = self;
blockview.myblock = ^(int a){
weakSelf.str = @"1";
return a;
};
3、 在 doSomething 内,weakSelf 不会被释放。但,下面的情况除外:
__weak __typeof__(self) weakSelf = self;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[weakSelf doSomething];
[weakSelf doOtherThing];
});
在 doSomething 中,weakSelf 不会变成 nil,不过在 doSomething 执行完成,调用第二个方法 doOtherThing 的时候,weakSelf 有可能被释放,于是,strongSelf 就派上用场了:
__weak __typeof__(self) weakSelf = self;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
__strong __typeof(self) strongSelf = weakSelf;
[strongSelf doSomething];
[strongSelf doOtherThing];
});
__strong
确保在 Block 内,strongSelf 不会被释放。
如有错误欢迎批评指正