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(@"%@
", 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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…