Search code examples
objective-cxcodemacosiboutletapplescript-objc

Objective-C | Outlet Collection OSX


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]


Solution

  • 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];
    }