为有牺牲多壮志,敢教日月换新天。

[Objective-C语言教程]快速枚举(35)

热烈欢迎,请直接点击!!!

进入博主App Store主页,下载使用各个作品!!!

注:博主将坚持每月上线一个新app!!!

快速枚举是Objective-C的功能,用于枚举集合。 因此,要了解快速枚举,首先需要了解集合,这将在下一节中进行说明。

1. Objective-C集合

集合是基本结构。它用于保存和管理其他对象。 集合的主要目的是提供一种有效存储和检索对象的通用方法。

有几种不同类型的集合。 虽然它们都能实现能够容纳其他对象的相同目的,但它们的主要区别在于检索对象的方式。 Objective-C中使用的最常见的集合是 -

  • NSSet
  • NSArray
  • NSDictionary
  • NSMutableSet
  • NSMutableArray
  • NSMutableDictionary

如果想了解有关这些结构的更多信息,请参阅Foundation框架中的数据存储。

快速枚举语法

1 for (classType variable in collectionObject ) { 
2   statements 
3 }

以下是快速枚举的示例 -

 1 #import <Foundation/Foundation.h>
 2 
 3 int main() {
 4    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
 5    NSArray *array = [[NSArray alloc]
 6    initWithObjects:@"string1", @"string2",@"string3",@"yii",@"bai",nil];
 7 
 8    for(NSString *aString in array) {
 9       NSLog(@"Value: %@",aString);
10    }
11 
12    [pool drain];
13    return 0;
14 }

执行上面示例代码,得到以下结果 -

1 2018-11-16 06:09:09.615 main[180842] Value: string1
2 2018-11-16 06:09:09.618 main[180842] Value: string2
3 2018-11-16 06:09:09.618 main[180842] Value: string3
4 2018-11-16 06:09:09.618 main[180842] Value: yii
5 2018-11-16 06:09:09.618 main[180842] Value: bai

如在输出中看到的那样,数组中的每个对象都按顺序打印。

快速枚举向后

1 for (classType variable in [collectionObject reverseObjectEnumerator] ) { 
2   statements 
3 }

以下是快速枚举中reverseObjectEnumerator的示例 -

 1 #import <Foundation/Foundation.h>
 2 
 3 int main() {
 4    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
 5    NSArray *array = [[NSArray alloc]
 6    initWithObjects:@"string1", @"string2",@"string3",@"Yii",@"Bai",nil];
 7 
 8    for(NSString *aString in [array reverseObjectEnumerator]) {
 9       NSLog(@"Value: %@",aString);
10    }
11 
12    [pool drain];
13    return 0;
14 }

执行上面示例代码,得到以下结果 -

1 2018-11-16 06:11:46.903 main[43643] Value: Bai
2 2018-11-16 06:11:46.904 main[43643] Value: Yii
3 2018-11-16 06:11:46.905 main[43643] Value: string3
4 2018-11-16 06:11:46.905 main[43643] Value: string2
5 2018-11-16 06:11:46.905 main[43643] Value: string1

正如您在输出中看到的那样,与正常快速枚举相比,数组中的每个对象都以相反的顺序打印。

posted @ 2019-03-21 16:50  为敢技术  阅读(165)  评论(0编辑  收藏  举报