在 Objective C 中使用 for-in 循环访问特定类型的对象 [英] Access objects of a specific type using for-in loop in Objective C

查看:55
本文介绍了在 Objective C 中使用 for-in 循环访问特定类型的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 NSMutableArray 上运行 for-in 循环.数组中还有A 类的实例,其中一些实际上是其子类B 的实例.

I am running a for-in loop over an NSMutableArray. There are instances of Class A in the array also out of those some are actually instances of its subclass B.

所以如果我只想要子类 B 的成员,我会检查我在循环体内的 if 条件中获得的每个对象的类.

So If I only want members of subclass B, I am checking the class of each object I get in an if condition inside the loop body.

有没有可能,而不是写这样的东西,

Is it possible that instead of writing something like this,

for(A* obj in collection){
    if([obj isKindOfClass:[B class]]){
        //take some action.
    }
}

我可以做这样的事情吗?

I can do something like this?

   for(B* obj in collection){
      //take some action.
   }

我会得到相同的结果吗?

Will I get the same result?

推荐答案

我可以做这样的事情吗...

Can I do something like this...

不,您不能在快速枚举中使用索引变量的类型来仅选择集合中的某些对象.如果集合包含不同类型的对象,则必须首先测试每个对象.但是,与测试类成员资格不同,使用 -respondsToSelector:-conformsToProtocol 而不是 -isKindOfClass 来测试您正在寻找的行为通常更好:.

No, you can't use the type of the index variable in fast enumeration to select only some of the objects in the collection. If the collection contains different types of objects, you'll have to test each object first. Instead of testing class membership, though, it's often nicer to test for the behavior you're looking for with -respondsToSelector: or -conformsToProtocol instead of -isKindOfClass:.

这篇关于在 Objective C 中使用 for-in 循环访问特定类型的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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