- 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 的一项功能,可帮助枚举某个集合。因此,为了了解快速枚举,我们首先需要了解集合,我将在接下来的部分中对此进行解释。
Objective-C 中的集合
集合是基本结构。其用于保存和管理其他对象。集合的全部目的是提供一种既定方式,以便高效地存储和检索对象。
有数种不同类型的集合。尽管它们都履行了容纳其他对象的相同职责,但它们的主要区别在于检索对象的方式。Objective-C 中使用最常见的集合是:
- NSSet
- NSArray
- NSDictionary
- NSMutableSet
- NSMutableArray
- NSMutableDictionary
如果你想了解有关这些结构的更多信息,请参阅 Foundation Framework 中的数据存储。
快速枚举语法
for (classType variable in collectionObject ) {
statements
}
以下是一个快速枚举示例。
#import <Foundation/Foundation.h>
int main() {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSArray *array = [[NSArray alloc]
initWithObjects:@"string1", @"string2",@"string3",nil];
for(NSString *aString in array) {
NSLog(@"Value: %@",aString);
}
[pool drain];
return 0;
}
现在当我们编译并运行程序时,我们将获得以下结果。
2013-09-28 06:26:22.835 demo[7426] Value: string1 2013-09-28 06:26:22.836 demo[7426] Value: string2 2013-09-28 06:26:22.836 demo[7426] Value: string3
正如你从输出中看到的那样,数组中的每个对象都会按序打印出来。
反向快速枚举
for (classType variable in [collectionObject reverseObjectEnumerator] ) {
statements
}
以下是在快速枚举中使用 reverseObjectEnumerator 的示例。
#import <Foundation/Foundation.h>
int main() {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSArray *array = [[NSArray alloc]
initWithObjects:@"string1", @"string2",@"string3",nil];
for(NSString *aString in [array reverseObjectEnumerator]) {
NSLog(@"Value: %@",aString);
}
[pool drain];
return 0;
}
现在当我们编译并运行程序时,我们将获得以下结果。
2013-09-28 06:27:51.025 demo[12742] Value: string3 2013-09-28 06:27:51.025 demo[12742] Value: string2 2013-09-28 06:27:51.025 demo[12742] Value: string1
正如你从输出中看到的那样,将打印出数组中的每个对象,但与常规快速枚举相比,顺序是相反的。
广告