对于对象继承的集合中的对象
在 Objective-C 中,
for (Foo *foo in fooList) ...
更像是以下哪一个
@interface Bar : Foo ...
for (Foo *f in fooList) {
// A:
if ([f isMemberOfClass:[Foo class]]) ... // dont include Bar's
// B:
if ([f isKindOfClass:[Foo class]]) ... // both Foos and Bars
}
In objective-c, is
for (Foo *foo in fooList) ...
more like which of the following
@interface Bar : Foo ...
for (Foo *f in fooList) {
// A:
if ([f isMemberOfClass:[Foo class]]) ... // dont include Bar's
// B:
if ([f isKindOfClass:[Foo class]]) ... // both Foos and Bars
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
也不像。
for() 部分中的 foo 的类型只是对编译器的一个提示,以便编译器给出相关的错误消息。在运行时,所有对象都只是对象,只要它们都实现了块中使用的方法,就不会出现错误。例如:
将迭代数组中的所有对象,并将 intValue 发送给每个对象,无论它们是什么类型,包括末尾的 NSString。如果每个对象都实现了 intValue ,它就会正常工作(就像 NSString 那样)。如果数组中有一个对象没有实现intValue,则很可能会抛出异常。
It's not like either.
The type of
foo
in thefor()
part is only a hint to the compiler so it can give out the relevant error messages. At run time, all the objects are just objects and as long as they all implement the methods used in the block, there will be no errors. For example:will iterate over all the objects in the array and send intValue to each one no matter what type they are including the NSString at the end. If every object implements
intValue
it will work just fine (as NSString does). If there is an object in the array that does not implement intValue, an exception will most likely be thrown.如果我理解正确的话,您是在问
for (Foo *foo in fooList)
是否会迭代fooList
中属于类Foo< 的成员的项目子集/code> 或类
Foo
的项目子集。答案是:没有。快速枚举(for...in)将迭代集合中的所有项目。它不会过滤
Foo
类型的对象。If I understand correctly, you are asking whether
for (Foo *foo in fooList)
will iterate over the subset of items infooList
that are members of classFoo
or the subset of items that are kind of classFoo
.The answer is: None. Fast enumeration (for... in) will iterate over all the items in the collection. It will not filter the objects of type
Foo
.