开发者

for object in collection where object inherits

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 开发者_Go百科isKindOfClass:[Foo class]]) ... // both Foos and Bars
}


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜