for object in collection where object inherits

邮差的信 提交于 2019-12-11 02:01:50

问题


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
}

回答1:


It's not like either.

The type of foo in the for() 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:

NSString* aString = @"20";
[anArray addObject: aString];
for (NSNumber* foo in anArray)
{
    NSLog(@"%d", [foo intValue]);
}

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.




回答2:


If I understand correctly, you are asking whether for (Foo *foo in fooList) will iterate over the subset of items in fooList that are members of class Foo or the subset of items that are kind of class Foo.

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.



来源:https://stackoverflow.com/questions/6694133/for-object-in-collection-where-object-inherits

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!