• [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

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

  • 相关阅读:
    Pymongo
    asp.net mvc4 使用java异步提交form表单时出现[object object] has no method ajaxSubmit
    C# Activator.CreateInstance()
    GridView中某一列值的总和(web)
    02.[WPF]如何固定窗口的大小
    01.WPF中制作无边框窗体
    C#.net时间戳转换
    org.springframework.beans.factory.BeanCreationException: 求教育!
    log4Net配置详解
    SQL语句-创建索引
  • 原文地址:https://www.cnblogs.com/strengthen/p/10572718.html
Copyright © 2020-2023  润新知