Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast Enumeration on NSArray of Different Types

I have this question here (as well other quesrtions on SO), and the Apple docs about Objective-C collections and fast enumeration. What is not made clear is if an NSArray populated with different types, and a loop is created like:

for ( NSString *string in myArray )
    NSLog( @"%@\n", string );

What exactly happens here? Will the loop skip over anything that is not an NSString? For example, if (for the sake of argument) a UIView is in the array, what would happen when the loop encounters that item?

like image 215
Mike D Avatar asked Dec 09 '11 22:12

Mike D


1 Answers

Why would you want to do that? I think that would cause buggy and unintended behavior. If your array is populated with different elements, use this instead:

for (id object in myArray) {
    // Check what kind of class it is
    if ([object isKindOfClass:[UIView class]]) {
       // Do something
    }
    else {
       // Handle accordingly
    }
}

What you are doing in your example is effectively the same as,

for (id object in myArray) {
    NSString *string = (NSString *)object;
    NSLog(@"%@\n", string);
}

Just because you cast object as (NSString *) doesn't mean string will actually be pointing to an NSString object. Calling NSLog() in this way will call the - (NSString *)description method according to the NSObject protocol, which the class being referenced inside the array may or may not conform to. If it conforms, it will print that. Otherwise, it will crash.

like image 189
john Avatar answered Sep 25 '22 19:09

john