您的位置:首页 > 编程语言

代码块

2015-11-08 00:00 218 查看
代码块的学习
个人认为代码块的好处就是简单明了,看起来更加清晰!
它的写法是
返回整形值( ^ 名字 )参数类型 = ^ (返回类型和名称){
代码块的整体}
//无返回类型
void (^hello_world)(void)= ^(void)
{
NSLog(@"hello world!");
};
hello_world();

void (^block)(int) = ^(int number1){
NSLog(@"%i",number1);
};
block(1);

//有返回类型
int (^square)(int) = ^(int number) {
return number*number;
};
int num = square(5);
NSLog(@"%i",num);

//构造块的关键字typedef ,优点是使代码看起来更加简洁。
typedef void (My_BLOCK)(void);
My_BLOCK block1 =(void){
NSLog(@"hello world");
};
block1();

typedef void (^SUM)(int);
SUM sum1 = ^(int number){
NSLog(@"%i",number);
};
sum1(3);

// 传多个参数的代码块
int (^add_Sum)(int,int)= ^(int num1,int num2){
return num1+num2;
};
int a = add_Sum(12,2);

NSLog(@"%i",a);

int addSum = 0;
for (int i = 1; i<=10; i++) {
addSum = add_Sum(addSum,i);
};
NSLog(@"%i",addSum);

//根据ASCALL码值来进行排序
NSArray *array = 
[
"q",
"w",
"e",
"r",
"t",
"y",
"u",
"i",
"o",
"p",
"a",
"s",
"d",
"f",
"g",
"h",
"j",
"k",
"l",
"z",
"x",
"c",
"v",
"b",
"n",
"m"];
NSArray *arr = [array sortedArrayUsingComparator:^NSComparisonResult(id
obj1, id  _Nonnull obj2) {
return [obj1 compare:obj2];
}];
NSLog(
"%@",arr);

//局部变量
double a = 10 , b = 20;
double (^result_w)(void) = ^(void){
return  a * b;
};
NSLog(
"%.0f",result_w());
a = 20;
b = 50;
NSLog(
"%.0f",result_w());
// static静态 全局变量
static double a1 = 1 , b1 = 2;
double (^result_ww)(void) = ^(void){
return a1 * b1;
};
NSLog(
"%.0f",result_ww());
a1 = 27;
b1 = 92;
NSLog(
"%.0f",result_ww());

static void (^const blocks)(int) = ^(int i)
{
if (i > 0)
{
NSLog(@"i:%d",i);
blocks(i-1);
}
};
blocks(10);

static int global = 2;
void(^blockI)(void) = ^(void)
{
global++;
NSLog(
"global:%d",global);
};
blockI();
NSLog(
"%d",global);

//本地变量会被代码块作为常量获取,如果需要修改他们的值,必须将他们声明为可修改的(__block)
__block double c = 3;
double (^he)(double,double) = ^(double a,double b){
c = a * b;
return c;
};
NSLog(@"%.0f",he(3,4));

static定义 ,一旦在前面写了static在往后的代码块中,就不能进行更改!出去了作用域,就会变味原值
在代码快中 改变局部变量编译是通不过的,需要在前面加 __block 关键字,否则会报这样的一个错误
递归使用
1: 用sataic 关键字 使其在真个类初始化之前初始化好
2: 使用 __block 关键字
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: