Block是objective c里的一种对象,他可以向c语言函数一样有参数,有返回值。Block对象集合了面向过程编程和面向对象编程的特点,和方法或函数类似,block对象也是一段可执行代码,可以接受实参并返回单个的参数值,于此同时,block对象也是对象,这种奇特的组合促成了默写新的设计模式,而这些设计模式是之前仅用函数和对象(以及对象的方法)很难实现的。
简单的block实例
// Defining a block variable
BOOL (^isInputEven)(int) = ^(int input) {
if (input % 2 == 0) {
return YES;
} else {
return NO;
}
};
这是一个名为isInputEven的Block变量,他接收一个int类型的参数然后返回一个BOOL类型的值,而等号后的int intput参数就是等号前的int参数,也就是你调用这个isInputEven Block时传入的值,可以在代码段内进行一些逻辑处理和数据分析,然后返回响应的结果,这就是Block的声明方法。
Block的另一个神奇之处在是,Block外的变量也可以在Block内部使用
例如
float price = 1.99;
float (^finalPrice)(int) = ^(int quantity) {
// Notice local variable price is
// accessible in the block
return quantity * price;
};
int orderQuantity = 10;
float price = 0.99;
NSLog(@"Ordering %d units, final price is: $%2.2f", orderQuantity, finalPrice(orderQuantity));
这就说明你的Block可以使用在该文件作用域内声明的局部变量了,这是个相当好的结果,不过需要注意的是,你并不能在Block内部去改变Block外部声明变量的值,这会是编译器立马报错。
而且在声明Block变量后如果你再次改变局部变量的值,结果和之前相比较并不会有区别,因为Block在声明时调用的局部变量其实是复制的过程,而你改变Block外部的变量是不能对内部副本起作用的。
例如,当你这样改变上述代码后结果是不会有变化的
float price = 1.99;
float (^finalPrice)(int) = ^(int quantity) {
// Notice local variable price is
// accessible in the block
return quantity * price;
};
int orderQuantity = 10;
NSLog(@"Ordering %d units, final price is: $%2.2f", orderQuantity, finalPrice(orderQuantity));
输出的结果为Ordering 10 units, final price is: $19.90
怎样来解决这个缺点呢