0

Basically I have a bunch of variables in my project, whose names are identical, only a number is different. I have to write a code, which is almost the same for all the variables, but a number changes. The actual problem is that all these variables are outlet connected to objects in IB. Example:

-(IBAction)setImages:(id)sender {

   int key = (int)[sender tag];
   if (key == 1) {
    [imageView1 setImage:myImage];
   } else if (key == 2) {
    [imageView2 setImage:myImage];
   } else if (key == 3) {
    [imageView3 setImage:myImage];
   }

}

What I would like is something like:

-(IBAction)setImages:(id)sender {

    int key = (int)[sender tag];
    [imageView(key) setImage:myImage];

}

This is just an example, not really what is in my code, and I am writing in AppleScriptObjC.

Any help would be really appreciated!

Thanks in advance

[EDITED THE CODE to explain better what I need]

2 Answers2

0

sender is the button object, just use that.

-(IBAction)setNames:(id)sender {

    int key = (int)[sender tag];
    [sender setTitle:[NSString stringWithFormat:@"Clicked Button %d", key]];
}

Edit: OK, I see you've changed the code in the question. How about building a dictionary that correlates button tags to image views? So, something like this:

@property( strong, nonatomic ) NSMutableDictionary* imageViews;

...

- (void) viewDidLoad {
    // Set up the dictionary here.
    self.imageViews = [NSMutableDictionary dictionary];
    self.imageViews[@(1)] = imageView1;
    self.imageViews[@(2)] = imageView2;
    ...
    self.imageViews[@(20)] = imageView20;
}

- (IBAction) setImages:(id)sender {
    int key = (int)[sender tag];
    NSImageView* imageView = self.imageViews[@(key)];
    [imageView setImage:myImage];
}
zpasternack
  • 17,838
  • 2
  • 63
  • 81
0

You can use Key-Value Coding for this:

-(IBAction)setImages:(id)sender {
   int tag = (int)[sender tag];
   NSString* key = [NSString stringWithFormat:@"imageView%d", tag];
   NSImageView* imageView = [self valueForKey:key];
   imageView.image = myImage;
}

Or, roughly equivalently:

-(IBAction)setImages:(id)sender {
   int tag = (int)[sender tag];
   NSString* keyPath = [NSString stringWithFormat:@"imageView%d.image", tag];
   [self setValue:myImage forKeyPath:keyPath];
}
Ken Thomases
  • 88,520
  • 7
  • 116
  • 154
  • The second alternative worked perfectly even in AppleScriptObjC, in the first you forgot to complete the argument of "forKeyPath:", but in spite of this, gives me an error. – Matteo La Mendola Jul 03 '15 at 07:14
  • Oops. That partial line was not supposed to be there at all in the first version, but I neglected to delete it. I've fixed it. – Ken Thomases Jul 03 '15 at 07:23