在不同类型的NSArray上快速枚举 [英] Fast Enumeration on NSArray of Different Types

查看:94
本文介绍了在不同类型的NSArray上快速枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在此处(以及关于SO的其他疑问)和苹果公司有关Objective-C集合的文档中有这个问题和快速的枚举.还不清楚的是NSArray是否填充了不同的类型,并且是否创建了像这样的循环:

I have this question here (as well other quesrtions on SO), and the Apple docs about Objective-C collections and fast enumeration. What is not made clear is if an NSArray populated with different types, and a loop is created like:

for ( NSString *string in myArray )
    NSLog( @"%@\n", string );

这里到底发生了什么?循环会跳过不是NSString的任何内容吗?例如,如果(出于参数考虑)数组中有一个UIView,那么当循环遇到该项目时会发生什么?

What exactly happens here? Will the loop skip over anything that is not an NSString? For example, if (for the sake of argument) a UIView is in the array, what would happen when the loop encounters that item?

推荐答案

为什么要这么做?我认为这会导致越野车和意外行为.如果您的数组中填充了其他元素,请改用此方法:

Why would you want to do that? I think that would cause buggy and unintended behavior. If your array is populated with different elements, use this instead:

for (id object in myArray) {
    // Check what kind of class it is
    if ([object isKindOfClass:[UIView class]]) {
       // Do something
    }
    else {
       // Handle accordingly
    }
}

您在示例中所做的实际上与

What you are doing in your example is effectively the same as,

for (id object in myArray) {
    NSString *string = (NSString *)object;
    NSLog(@"%@\n", string);
}

仅仅因为将object强制转换为(NSString *)并不意味着string实际上将指向NSString对象.以这种方式调用NSLog()将根据

Just because you cast object as (NSString *) doesn't mean string will actually be pointing to an NSString object. Calling NSLog() in this way will call the - (NSString *)description method according to the NSObject protocol, which the class being referenced inside the array may or may not conform to. If it conforms, it will print that. Otherwise, it will crash.

这篇关于在不同类型的NSArray上快速枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆