Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does fast enumeration not skip the NSNumbers when I specify NSStrings?

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];

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

I logged only the NSStrings, but I get a line for every object in the array, even the NSNumbers and I don't understand why. Does fast enumeration always use every object contained in an array?

like image 279
greg.bzh Avatar asked Nov 27 '22 14:11

greg.bzh


1 Answers

When you write a forin loop like that, it casts every object in the array as an NSString, then prints them out as requested.

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);
    }
}
like image 97
Katfish Avatar answered Dec 22 '22 08:12

Katfish