//
//main.m
//Block
//
//Created by DioneFlora on 16/10/20.
//Copyright (c) 2016年DioneFlora. All rights reserved.
//
#import <Foundation/Foundation.h>
//block块(数据类型):封装了一段具有特定功能的代码段
//函数有函数名,block是没有名字的,也可以叫做匿名函数;函数不能作为参数传递,block可以作为参数传递
//return(如果返回值类型不是void就必须将返回值return出去)
//形式:
/*
返回值类型(^block变量名)(参数列表)=^(参数列表){
代码段
}
*/
//调用
//block变量名()
//这是一个无参无返的block
voiddemoOne(){
//无参无返的block(写一个block,用for循环打印三遍“Hello World!”)
//定义一个block
void(^myBlock)() = ^(){
for(inti =0; i <3; i++) {
NSLog(@"Hello World!");
}
};
//调用一个block
myBlock();
}
//这是一个有参无返的block
/*
void(^block名)(参数列表)=(参数列表){}
*/
voiddemoTwo(){
//定义一个block,用for循环打印N次Hello World!,n用键盘输入
void(^youBlock)(intn) = ^(intn){
for(inti =0; i < n; i++) {
NSLog(@"Hello World!");
}
};
intnumber;
NSLog(@"请输入一个整数:\n");
scanf("%d",&number);
//调用一个block
youBlock(number);
}
//无参有返的block
/*
返回值类型(^block名)()=^(){}
*/
voiddemoThree(){
int(^peopleCount)() = ^(){
return28;
};
//调用
intcount = peopleCount();
NSLog(@"count = %d",count);
//定义一个block返回字符串hello
char* (^string)() = ^(){
return"hello";
};
char*str = string();
NSLog(@"str = %s",str);
}
voiddemoFour(){
//有参有返的block
//写4个block来做四则运算(+,-,*,/),a,b两个值通过键盘输入
int(^addCount)(intn,intm) = ^(intn,intm){
returnn + m;
};
int(^delCount)(intn,intm) = ^(intn,intm){
returnn - m;
};
int(^mulCount)(intn,intm) = ^(intn,intm){
returnn * m;
};
int(^chuCount)(intn,intm) = ^(intn,intm){
if(m ==0){
NSLog(@"除数不能为0");
return0;
}
returnn / m;
};
inta,b;
NSLog(@"请输入两个数:\n");
scanf("%d%d",&a,&b);
intadd = addCount(a,b);
NSLog(@"add = %d",add);
intdel = delCount(a,b);
NSLog(@"del = %d",del);
intmul = mulCount(a,b);
NSLog(@"mul = %d",mul);
intchu = chuCount(a,b);
NSLog(@"chu = %d",chu);
}
//diyBlock是给int(^)(int a,int b)这种block类型定义的一个新名字,以后我们使用diyBlock就表示int(^)(int a,int b)这个类型
typedefint(^diyBlock)(inta,intb);
voiddemoFive(){
diyBlock addBlock = ^(inta,intb){
returna + b;
};
diyBlock jianBlock = ^(inta,intb){
returna - b;
};
diyBlock chengBlock = ^(inta,intb){
returna * b;
};
diyBlock chuBlock = ^(inta,intb){
returna / b;
};
inta,b;
NSLog(@"请输入两个数:\n");
scanf("%d%d",&a,&b);
intadd = addBlock(a,b);
NSLog(@"add = %d",add);
intjian = jianBlock(a,b);
NSLog(@"jian = %d",jian);
intcheng = chengBlock(a,b);
NSLog(@"cheng = %d",cheng);
intchu = chuBlock(a,b);
NSLog(@"chu = %d",chu);
}
intmain(intargc,constchar* argv[]) {
@autoreleasepool{
demoOne();
demotwo();
demoThree();
demoFour();
demoFive();
}
return0;
}