#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