块操作 Block
2015-12-24 16:07 AB小博客 阅读(205) 评论(0) 编辑 收藏 举报// // main.m // 块操作 Block // // Created by MAC on 15/12/24. // Copyright © 2015年 MAC. All rights reserved. // #import <Foundation/Foundation.h> int main(int argc, const char * argv[]) { @autoreleasepool { /* 1.Block [] 匿名函数 闭包 c叫函数指针 2.Block语法格式 return type (^BlockName)(list of arguments)=^(list of arguments){body} */ void(^TestBlock)(void)=^(void){ NSLog(@"Hello Block"); }; TestBlock(); int(^SumBlock)(int a,int b)=^(int a,int b){ return a+b; }; NSLog(@"sum =%d",SumBlock(1,2)); //访问外部变量 要加__block __block int x =100; void(^ChangeBolck)(void)=^(void){x=200;}; ChangeBolck(); NSLog(@"x=%d",x); //3.如何直接使用Block NSArray *array = @[@"4",@"2",@"5",@"9"]; //进行排序 array = [array sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) { return [obj1 compare:obj2]; }]; NSLog(@"%@",array); //4.类型定义typedif typedef void (^MyBlock)(void); MyBlock b = ^(void){NSLog(@"Hello World");}; b(); typedef int (^Sumblock)(int a,int b); Sumblock s = ^(int a,int b){return a+b;}; s(1,5); //5.本地变量在代码块的作用域(常量) __block int a = 100,c= 200; //常量使用 const int(^Sunblock1)(void)=^(void){return a+c;};//使用第一次的值 100 200 后面值的改变不会影响 NSLog(@"%d",Sunblock1()); a = 22; c = 22; NSLog(@"%d",Sunblock1());//结果都是300 //6.全局变量 static int aa = 100,cc= 200; //设定为static 都可以访问 int(^Sunblock2)(void)=^(void){return aa+cc;}; NSLog(@"%d",Sunblock2()); aa = 22; cc = 22; int xx = Sunblock2(); NSLog(@"%d",xx);//结果44 } return 0; }