2.Block实战

2.Block实战

问题来自:iOS开发基础:开发两年的你也不会写的Block

  1. 声明一个Block,并调用它。
  2. 声明一个Block型的属性。
  3. 声明一个方法,接受一个Block型的参数,并写出调用时传入的Block实参。
  4. 实现一个Block的递归调用(Block调用自己)。
  5. 实现一个方法,将Block作为返回值。

1. 声明block,并使用

// 返回值类型+(^block名)(参数列表) = ^返回值类型(参数列表){...};
NSInteger (^sumBlock)(NSInteger, NSInteger) = ^NSInteger (NSInteger a, NSInteger b) {
    return a + b;
};

NSInteger sum = sumBlock(1, 2);
NSLog(@"sum = %@", @(sum));

2.声明Block型的属性

// 其实和局部变量的声明是相同的,注意使用copy
@property (nonatomic, copy) NSString* (^appendStringBlock)(NSString *title);

3.Block类型的方法参数

相比于Block型的属性形式,只需要将^后面的block名提到最后即可

// 返回值类型(^)(参数列表)block名
- (void)declareAMethodWithBlock:(BOOL(^)(NSInteger index))callBackBlock {
    NSInteger idx = 0;
    while (callBackBlock(idx)) {
        NSLog(@"%@", @(idx));
        idx = idx + 1;
    }
}

// 方法调用
[self declareAMethodWithBlock:^BOOL(NSInteger index) {
    return index < 10;
}];

4.Block递归调用

__block NSInteger number = 0;
__block void (^calculateSum) (NSInteger) = ^void (NSInteger input) {
    number = input + 1;
    if (number >= 10) {
        calculateSum = nil;
        return;
    }
    calculateSum(number);
};

calculateSum(1);
NSLog(@"%@", @(number));

5.Block作为返回值

- (NSInteger (^) (NSInteger))returnBlockType {
    return ^ NSInteger (NSInteger a){
        return  a * a;
    };
}

NSLog(@"%@", @([self returnBlockType](20)));

推荐一个网站

How Do I Declare A Block in Objective-C?,记不住block的时候可以参考一下

posted @ 2020-11-23 15:15  小小个子大个头  阅读(103)  评论(0编辑  收藏  举报