#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
/**
* 块的基础知识
*/
// return_type (^block_name)(parameters)
int (^block_Name)() = ^(int a,int b){
return a+b;
};
int add = block_Name(2,5);
NSLog(@"%d",add);//7
//块的强大之处在于:在声明它的范围里,所有变量都可以为其捕获。
int (^addBlock)(int a, int b) =^(int a, int b){
return a+b+add;
};
int addTwo = addBlock(2,5);
NSLog(@"%d",addTwo);
//块内修改变量
NSArray *array =@[@0,@1,@2,@3,@4,@5];
__block NSInteger count = 0;
[array enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
if ([obj compare:@2] == NSOrderedAscending){
count++;
}
}];
NSLog(@"%ld",count);
/**
* 块的内部结构
*/
/**
* 全局块,栈块,堆块
*/
//堆块
void (^block)();
BOOL flag = YES;
if (flag){
block = [^{
NSLog(@"Block A");
}copy];
}else{
block = [^{
NSLog(@"Block B");
}copy];
}
block();
}
@end
转载于:https://my.oschina.net/u/2319073/blog/638157