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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With