Objective-C中的代码块类似于其他编程语言中的闭包(closures)或匿名函数(anonymous functions)。它们允许你在代码中定义一段可执行的代码,然后将其作为参数传递给方法或函数。
Block的定义和声明:
- 语法格式:
returnType (^blockName)(parameterTypes) = ^returnType (parameters) {...};
/*
声明语法格式:returnType (^blockName)(parameterTypes) = ^returnType (parameters) {...};
*/
void (^printBlock)(void) = ^void (void) {
NSLog(@"hello world");
};
// 调用
printBlock();
Block应用示例:
- 在函数内部定义声明,并在函数内部调用,可以理解成函数内部的小分层策略
适用场景:函数内部有共用逻辑、函数内部再做细粒度的逻辑分层、且这些逻辑不会在函数外部调用或者说没有必要在外部调用,故把这些逻辑分层封装在函数内部,满足高内聚和单一原则。
/*
block在函数内部的使用
目的:分层
*/
- (void)blockInFunction {
// 逻辑分层
NSInteger (^addBlock)(NSInteger, NSInteger) = ^NSInteger (NSInteger number1, NSInteger number2) {
return number1 + number2;
};
NSInteger result = addBlock(1,2);
NSLog(@"%zd", result);
}
实战项目应用截图如下:
- 作为参数在函数调用中传递,这是block常用的方式
适用场景:事件回传,被调用的函数会在某个特定的时机调用这个block将一些信息回传给函数调用方
/*
block作为方法参数
目的:回传事件
*/
- (void)blockAsParamsInFunction:(void (^)(NSString *name, NSInteger age))callBackBlock {
callBackBlock(@"yu", 18);
}
//调用
[self blockAsParamsInFunction:^(NSString *name, NSInteger age) {
NSLog(@"name:%@ age:%zd", name, age);
}];
在AFNetworking框架中的应用截图如下:
Block与typedef搭配使用