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

前端 未结 8 1114
慢半拍i
慢半拍i 2021-01-14 02:27

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 NSNum

相关标签:
8条回答
  • 2021-01-14 02:30

    in fast enumeration no typecasting,just assigning the pointer into new object

    0 讨论(0)
  • 2021-01-14 02:33

    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);
        }
    }
    
    0 讨论(0)
  • 2021-01-14 02:35

    I don't understand where is the unexpected behavior, using the enhanced for loop in an NSMutableArray will just iterate thru every single object in the array which in your case is 6, the result is correct and expected.

    The numbers will just get casted to Strings.

    0 讨论(0)
  • 2021-01-14 02:37

    I'm pretty sure that fast enumeration returns all objects in the array- all that you're doing in for (NSString *str in array) is typecasting str to an NSString. In the body of the loop you need to check the class of the returned object to make sure that it is an NSString.

    for(NSString *str in array)
    {
        if([str isKindOfClass:[NSString class]])
            NSLog(@"str : %@", str);
    }
    
    0 讨论(0)
  • 2021-01-14 02:38

    Every object that descends from NSObject implements the method - (NSString)description, %@ in Objective-C formate string will take the corresponding argument for the %@ and call its description method, Most subclasses of NSObject will implement there own version of - (NSString)description. The same thing happens when you type

    > po anObject
    

    in the debugger.

    0 讨论(0)
  • 2021-01-14 02:45
    for (NSString *str in array) {
    

    is a way to enumerate through all the elements in array.

    You expectative that by specifying NSString you get only the objects of that type is not correct. Rather, all the objects pointers are cast to that type (NSString*).

    Have a look at Fast Enumeration in The Objective-C Programming Language guide.

    0 讨论(0)
提交回复
热议问题