0

I have an xib file with a number of views. Their IBOutlets are named view1, view2, view3, and so on, and I want to access them in a loop. Is it possible to do this in Objective-C?

I know in ActionScript you can generate an object's name like this: ["view"+num].

jscs
  • 63,694
  • 13
  • 151
  • 195
Nimrod Yizhar
  • 381
  • 4
  • 14

4 Answers4

3

Put them in an IBOutletCollection. This is an array, you can populate it in interface builder and iterate through it.

jrturton
  • 118,105
  • 32
  • 252
  • 268
2

Rather than naming them, assign them tags (0...10) then you can pull them out of the parent view with viewWithTag:.

Nick
  • 9,792
  • 7
  • 50
  • 60
1

Use key value coding. If say suppose I have view1 .. view 10, then I would use it like this;

for(int i=0 i< 10; i++){
  UIView *eachView = [self valueForKey:[NSString stringWithFormat:@"view%d", i]];
}

I hope it works for you.

Sandeep
  • 20,908
  • 7
  • 66
  • 106
0

Another way you can accomplish this is using NSDictionaryOfVariableBindings.

NSArray *views = [NSDictionaryOfVariableBindings(view1, view2, view3) allObjects];
for (UIView *item in views)
    do something with item;
paulmelnikow
  • 16,895
  • 8
  • 63
  • 114