为什么在指定NSStrings时快速枚举不跳过NSNumbers? [英] Why does fast enumeration not skip the NSNumbers when I specify NSStrings?
问题描述
我以为我知道如何使用快速枚举,但是对此我有些不了解.如果我创建三个NSString
对象和三个NSNumber
对象并将它们放在NSMutableArray
中:
I thought that I knew how to use fast enumeration, but there is something I don't understand about it. If I create three NSString
objects and three NSNumber
objects and put them in an NSMutableArray
:
NSString *str1 = @"str1";
NSString *str2 = @"str2";
NSString *str3 = @"str3";
NSNumber *nb1 = [NSNumber numberWithInt:1];
NSNumber *nb2 = [NSNumber numberWithInt:2];
NSNumber *nb3 = [NSNumber numberWithInt:3];
NSArray *array = [[NSArray alloc] initWithObjects:str1, str2, str3, nb1, nb2, nb3, nil];
然后我对所有NSString
对象进行快速枚举,如下所示:
then I make do fast enumeration on all NSString
objects, like this:
for (NSString *str in array) {
NSLog(@"str : %@", str);
}
在控制台中,我得到以下结果:
In the console, I get this result :
2011-08-02 13:53:12.873 FastEnumeration[14172:b603] str : str1
2011-08-02 13:53:12.874 FastEnumeration[14172:b603] str : str2
2011-08-02 13:53:12.875 FastEnumeration[14172:b603] str : str3
2011-08-02 13:53:12.875 FastEnumeration[14172:b603] str : 1
2011-08-02 13:53:12.876 FastEnumeration[14172:b603] str : 2
2011-08-02 13:53:12.876 FastEnumeration[14172:b603] str : 3
我只记录了NSString
,但是我得到了数组中每个对象的一行,甚至是NSNumber
,我也不明白为什么.快速枚举是否总是使用数组中包含的每个对象?
I logged only the NSString
s, but I get a line for every object in the array, even the NSNumber
s and I don't understand why. Does fast enumeration always use every object contained in an array?
推荐答案
当您编写这样的forin循环时,它会将数组中的每个对象强制转换为NSString,然后根据要求将其打印出来.
When you write a forin loop like that, it casts every object in the array as an NSString, then prints them out as requested.
如果只需要NSString,则需要编写如下内容:
If you want only the NSStrings, you would need to write something like this:
for (id obj in array) {
if ([obj isKindOfClass:[NSString class]]) {
NSLog(@"str: %@", obj);
}
}
这篇关于为什么在指定NSStrings时快速枚举不跳过NSNumbers?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!