zoukankan      html  css  js  c++  java
  • [Objective-C语言教程]快速枚举(35)

    快速枚举是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

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

  • 相关阅读:
    BZOJ4722 由乃
    LOJ6043 「雅礼集训 2017 Day7」蛐蛐国的修墙方案
    Luogu P2414 [NOI2011]阿狸的打字机
    Luogu P3193 [HNOI2008]GT考试
    Luogu P3167 [CQOI2014]通配符匹配
    Luogu P4503 [CTSC2014]企鹅QQ
    Luogu P5446 [THUPC2018]绿绿和串串
    Luogu P5329 [SNOI2019]字符串
    免密码ssh2登录
    mooon模板的automake、autoconf、m4和libtool版本信息
  • 原文地址:https://www.cnblogs.com/strengthen/p/10572718.html
Copyright © 2011-2022 走看看