- Objective-C 基础
- Objective-C - 首页
- Objective-C - 概述
- Objective-C - 环境设置
- Objective-C - 程序结构
- Objective-C - 基本语法
- Objective-C - 数据类型
- Objective-C - 变量
- Objective-C - 常量
- Objective-C - 运算符
- Objective-C - 循环
- Objective-C - 决策
- Objective-C - 函数
- Objective-C - 块
- Objective-C - 数字
- Objective-C - 数组
- Objective-C - 指针
- Objective-C - 字符串
- Objective-C - 结构体
- Objective-C - 预处理器
- Objective-C - Typedef
- Objective-C - 类型转换
- Objective-C - 日志处理
- Objective-C - 错误处理
- 命令行参数
- 高级 Objective-C
- Objective-C - 类与对象
- Objective-C - 继承
- Objective-C - 多态
- Objective-C - 数据封装
- Objective-C - 分类
- Objective-C - 模拟
- Objective-C - 扩展
- Objective-C - 协议
- Objective-C - 动态绑定
- Objective-C - 复合对象
- Obj-C - Foundation 框架
- Objective-C - 快速枚举
- Obj-C - 内存管理
- Objective-C 有用资源
- Objective-C - 快速指南
- Objective-C - 有用资源
- Objective-C - 讨论
Objective-C 块
Objective-C 类定义了一个将数据与相关行为结合起来的对象。有时,仅仅表示单个任务或行为单元而不是方法集合是有意义的。
块是添加到 C、Objective-C 和 C++ 的语言级特性,允许您创建可以像值一样传递给方法或函数的代码片段。块是 Objective-C 对象,这意味着它们可以添加到像 NSArray 或 NSDictionary 这样的集合中。它们还能够捕获封闭作用域中的值,这使得它们类似于其他编程语言中的闭包或 lambda。
简单的块声明语法
returntype (^blockName)(argumentType);
简单的块实现
returntype (^blockName)(argumentType)= ^{
};
这是一个简单的例子
void (^simpleBlock)(void) = ^{
NSLog(@"This is a block");
};
我们可以使用以下方式调用块:
simpleBlock();
块接受参数并返回值
块也可以像方法和函数一样接受参数并返回值。
这是一个实现和调用带参数和返回值的块的简单示例。
double (^multiplyTwoValues)(double, double) =
^(double firstValue, double secondValue) {
return firstValue * secondValue;
};
double result = multiplyTwoValues(2,4);
NSLog(@"The result is %f", result);
使用类型定义的块
这是一个在块中使用 typedef 的简单示例。请注意,此示例目前无法在在线编译器上运行。使用XCode运行相同的代码。
#import <Foundation/Foundation.h>
typedef void (^CompletionBlock)();
@interface SampleClass:NSObject
- (void)performActionWithCompletion:(CompletionBlock)completionBlock;
@end
@implementation SampleClass
- (void)performActionWithCompletion:(CompletionBlock)completionBlock {
NSLog(@"Action Performed");
completionBlock();
}
@end
int main() {
/* my first program in Objective-C */
SampleClass *sampleClass = [[SampleClass alloc]init];
[sampleClass performActionWithCompletion:^{
NSLog(@"Completion is called to intimate action is performed.");
}];
return 0;
}
让我们编译并执行它,它将产生以下结果:
2013-09-10 08:13:57.155 demo[284:303] Action Performed 2013-09-10 08:13:57.157 demo[284:303] Completion is called to intimate action is performed.
块更多地用于 iOS 应用程序和 Mac OS X。因此,理解块的使用非常重要。
广告