Search code examples
objective-coopprogramming-languages

Can I access elements/methods named "button1" "button2" "button3" etc. using "buttoni" inside a for-loop?


I have a bunch of buttons named:

button1
button2
button3
etc.

Is there a way to basically do this?

pseudocode
for(int i = 1, i < 15, i++) {
    button{i}.selected = YES;
}

This also goes for method calls, etc. I've often thought such a way of calling methods would be very convenient, but I don't think I've ever seen it done when using compiled languages. But I have done it using PHP.

Is there any way to do this in Objective-C? (That's where my problem is now, but I'd also be interested in if you can do this in other languages.) Alternately, is there a reason why this is NOT a good way to go about accessing all the UI elements?

Thanks!


Solution

  • In objective C you can put the elements in an NSArray, and more generally for any language, put the elements you want to iterate over in a collection.

    If you really want to do cute things with dynamic names, use an NSDictionary and look it up by a string name; this is pretty much what PHP does with its $$foo syntax anyway.

    #import <Foundation/Foundation.h>
    
    int
    main()
    {
      NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
      id button1 = @"this is button 1";// not actually buttons, but same principle
      id button2 = @"this is button 2";
      id button3 = @"this is button 3";
    
      NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                         button1, @"button1",
                         button2, @"button2",
                         button3, @"button3"];
    
      int i;
      for (i = 1; i <= 3; ++i) {
        // you can send messages to these objects instead of NSLogging them
        NSLog([dict objectForKey: [NSString stringWithFormat:@"button%d", i]]);
      }
    }