views:

17

answers:

1

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!

+2  A: 

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]]);
  }
}
p00ya
But... that's not based on the name of the object/method though, right? Any way to do what I said in the original post? I'm sure there are many other ways to loop through a bunch of objects...
cksubs
Methods are dynamic, you can turn an NSString into a selector easily. identifier names are just something for the compiler though. Make an NSDictionary if you want to have a string mapping like PHP.
p00ya
"Identifier names are just something for the compiler": indeed, they don't even have to *exist* at runtime. They might be there for debugging information, but nothing else.
Antal S-Z