1

If I have 100 UITextFields,

myTextfFeld1, myTextField2...and so on until mytextField100

...and they all perform the same action, say change myTextField1.alpha = 0.4 to myTextField1.alpha = 1.

Rather than write this out 100 times is there a more efficient way of doing this

I had a look here iOS looping over an object's properties and adding actions but it still means adding all the UITextFields into the array.

Community
  • 1
  • 1
JSA986
  • 5,870
  • 9
  • 45
  • 91

3 Answers3

6

Please, no!

Like this.

Use an array, seriously. Don't you dare having 100 instance variables named textField1 to textField100!


Just in order to actually answer your question: you still can do this. Again, I strongly discourage doing it, but just for completeness' sake, here's the code:

for (int i = 1; i <= 100; i++) {
    NSString *ivarName = [NSString stringWithFormat:@"myTextField%d", i];
    UITextField *tf = [self valueForKey:ivarName];
    [tf doWhateverYouWant];
}

Reflection in Objective-C is awesome, isn't it? Not quite when abused.

  • I would dream of it its just example text for SO – JSA986 Jun 23 '13 at 18:26
  • @JSA986 Sorry, I don't understand what you mean, please elaborate. –  Jun 23 '13 at 18:27
  • I wouldn't actually have a 100 instance variables named `myText1`etc. They were hypothetical instance variable for simplicity when posting my question. They have much better naming conventions than that ;-) Thanks for answer thats exactly was after! – JSA986 Jun 23 '13 at 18:30
1

You can define an outlet collection and connect all of the textfields to it from the XIB:

 @property (nonatomic, weak) IBOutletCollection(UITextField) NSArray *textFields;

Then you can loop over the textFields array.

Wain
  • 118,658
  • 15
  • 128
  • 151
  • ...or instead of looping, you can use the method `–makeObjectsPerformSelector:withObject:` on the `NSArray`. – holex Jun 23 '13 at 18:36
  • 1
    @holex, true, assuming that the method takes an object parameter (so couldn't be used for setting the `alpha` for example) – Wain Jun 23 '13 at 18:37
  • yep, you are absolutely right, it needs a little play with the `NSInvocation` for the non-object parameters. it depends on the code-pattern the poster has chosen, but that was not part of the original question, I think. – holex Jun 23 '13 at 19:06
-2

Use a loop and an array for the textfields. e.g.

int i = 0
do textfield[i].alpha = 1
i = i+1
until i = 100
user2369405
  • 217
  • 1
  • 4
  • 10
  • The question is tagged Objective-C. Answers should be in the same language. – rmaddy Jun 23 '13 at 18:38
  • Are you allowed? Sure. But to be helpful, your answer should provide usable code appropriate to the question. – rmaddy Jun 24 '13 at 04:34