首先必须明确的是:Block是一种数据类型。
关于数据类型,我们至少应该知道一种数据类型一般被拿来干什么:
(1)可以声明成变量
(2)可以作为参数传递
(3)可以作为函数的返回值
其实Block和一个指向函数的指针比较像。
不说别的,上代码:
一个简单的带返回值的Block小示例就这样产生了。
int (^myBlock)(int a, int b) = ^(int x, int y)
{
return x + y;
};
myBlock = ^(int x, int y)
{
return x + y;
};
int sum = myBlock(90, 10);
NSLog(@"---%d---", sum);
第二个示例是利用typedef定义一个Block类型的变量,然后将它作为参数进行传递。
//Calculator.h文件
#import <Foundation/Foundation.h>
typedef NSInteger (^calBlock)(NSInteger a, NSInteger b);
@interface Calculator : NSObject
- (NSInteger)calculateA:(NSInteger)a andB:(NSInteger)b andCalculateBlock:(calBlock)block;
@end
//Calculator.m文件
#import "Calculator.h"
@implementation Calculator
- (NSInteger)calculateA:(NSInteger)a andB:(NSInteger)b andCalculateBlock:(calBlock)myBlock
{
return myBlock(a,b);
}
@end
//Test2
//在开发中,当你发现一个方法中的算法可以有多种实现,你一时还不能确定用哪种更好的时候,你可以把它定义成
//一个Block,当你想好的时候,你再去实现它。
//实际这是一种思想,在Java、C#中,它叫虚方法或者抽象方法
NSInteger (^myBlock)(NSInteger a, NSInteger b) = ^(NSInteger x, NSInteger y)
{
return x + y;
};
Calculator *cal = [[Calculator alloc] init];
NSInteger sum = [cal calculateA:8 andB:8 andCalculateBlock:myBlock];
NSLog(@"***sum = %ld", sum);
NSInteger sum2 = [cal calculateA:88 andB:2 andCalculateBlock:^NSInteger(NSInteger a, NSInteger b) {
return a + b;
}];
NSLog(@"***sum2 = %ld", sum2);