Block的基本用法和写法1
/**
* •block书写规则:
1.返回值(^函数名)(参数类型) = ^返回值(参数)
•当block有返回值时,{}别忘了return,否则会报错
•回调函数(block1() block2(1,2) block3(2,3) block4(8,5))能够当做参数使用
*/
四种类型:
//————————————1.无返回值,无参数————————————
/**
没有返回值 没有参数
⬇️ ⬇️ */
void (^block1)() = ^{
NSLog(@"Hello world");
};
//回调——没有此行,不会打印
block1();
// 只有完成回调,才能执行block中的方法
//————————————————————————————————————————
//————————————2.无返回值,有参数————————————
void (^block2)(NSInteger,NSInteger) = ^(NSInteger i,NSInteger j){
NSLog(@"%ld",i+j);
};
block2(1,2);
//————————————————————————————————————————
//————————————3.有返回值,没参数————————————
NSString* (^block3)(NSInteger,NSInteger) = ^NSString* (NSInteger a,NSInteger b){
NSString *str = [NSString stringWithFormat:@"a+b的值是%ld",a*b];
NSLog(@"%@",str);
return str;
};
block3(2,3);
//————————————————————————————————————————
//————————————4.有返回值,无参数————————————
NSArray *(^block4)(NSInteger,NSInteger) = ^NSArray *(NSInteger index1,NSInteger index2){
NSMutableArray *mtbArr = [NSMutableArray array];
for (NSInteger i = 0; i<index1; i++) {
if (i==index2) {
NSLog(@"%ld不在此范围内",(long)index2);
}else{
NSString *str = [NSString stringWithFormat:@"index is %ld\n",i];
[mtbArr addObject:str];
}
}
return mtbArr;
};
NSArray *blockArr = block4(8,5);
for (NSString *j in blockArr) {
NSLog(@"%@",j);
}
//————————————————————————————————————————
以上block打印结果
2016-03-18 15:57:05.393 testUseCycscrollViewAddLunBoView[11419:226699] Hello world
2016-03-18 15:57:05.394 testUseCycscrollViewAddLunBoView[11419:226699] 3
2016-03-18 15:57:05.394 testUseCycscrollViewAddLunBoView[11419:226699] a+b的值是6
2016-03-18 15:57:05.394 testUseCycscrollViewAddLunBoView[11419:226699] 5不在此范围内
2016-03-18 15:57:05.395 testUseCycscrollViewAddLunBoView[11419:226699] index is 0
2016-03-18 15:57:05.395 testUseCycscrollViewAddLunBoView[11419:226699] index is 1
2016-03-18 15:57:05.395 testUseCycscrollViewAddLunBoView[11419:226699] index is 2
2016-03-18 15:57:05.395 testUseCycscrollViewAddLunBoView[11419:226699] index is 3
2016-03-18 15:57:05.396 testUseCycscrollViewAddLunBoView[11419:226699] index is 4
2016-03-18 15:57:05.396 testUseCycscrollViewAddLunBoView[11419:226699] index is 6
2016-03-18 15:57:05.396 testUseCycscrollViewAddLunBoView[11419:226699] index is 7
*/
_________________________________返回值可以省略______________________________
/*
以下三种方式,等价,返回值可以省略(都是不带参数的block)
void (^block3)() = ^void(){
};
void (^block3)() = ^(){
};
void (^block3)() = ^{
};
*/
//———————————————使用typedef定义一个别名,block当做参数使用————————————————
//typedef void(^MyBlock)();——————例子为无参数,无返回值得block
MyBlock otherNameBlock = ^(){
NSLog(@"Hello China");
};
otherNameBlock();