Objective-C |奥特莱斯精选 OSX

Objective-C | Outlet Collection OSX

基本上我的项目中有一堆变量,名称相同,只是数字不同。我必须编写一个代码,所有变量几乎相同,但有一些变化。实际问题是所有这些变量都连接到 IB 中的对象。 示例:

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

}

我想要的是这样的:

-(IBAction)setImages:(id)sender {

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

}

这只是一个示例,并不是我的代码中的真实内容,我正在用 AppleScriptObjC 编写。

非常感谢任何帮助!

提前致谢

[编辑代码以更好地解释我的需要]

sender是按钮对象,就用那个。

-(IBAction)setNames:(id)sender {

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

编辑:好的,我看到你已经更改了问题中的代码。如何构建一个将按钮标签与图像视图相关联的字典?所以,像这样:

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

您可以为此使用键值编码:

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

或者,大致等价于:

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