Which is the correct way of enumerating through sub views to find text fields?
NSMutableArray *mutableTFs = [[NSMutableArray alloc] init];
for (UIView *view in [self.view subviews]) {
if ([view isKindOfClass:[UITextField class]]) {
[mutableTFs addObject:view];
}
}
OR
NSMutableArray *mutableTFs = [[NSMutableArray alloc] init];
for (UITextField *textField in [self.view subviews]) {
[mutableTFs addObject:textField];
}
I know this isn't the correct wording, but what I don't understand is if it is the top method, how do you 'convert' it from a view to a text field?
The first method is the only working method of the two.
The second method would add all subviews to the array. That is if you would change
subViews
tosubviews
.You could do the following:
That way you wouldn't have to convert the view to a text field to do something text field specific instead of just adding it to an array.
EDIT: If you don't want to convert to a text field right away, maybe because you're looking for both text fields and text views. This is how you'd convert it later:
The first method is the correct one. The second method will iterate over all the subviews, not just the subviews with type
UITextField
. The type in thefor()
is only a hint to the compiler.For more information, see this question.
This is what typecasting is for.
Here's the best way.
By specifying
UITextField *
as the type that you're performing the fast enumeration with, you'll be working with values that are casted already (by fast enumeration) from id toUITextField *
. This does not guarantee that they are actually UITextFields though, so you still need a runtime check, in this caseisKindOfClass:
, to make sure the object you're currently working is really aUITextField
.So, both of them are correct, but only when combined.