views:

13

answers:

1

Say I have 5 UIImageViews, named image1 image2 image3 image4 and image5.

And I have 5 buttons, which have their tag values set to the corresponding images that overlay them, so 1 - 5.

If button 1 is pressed, I get the tag value like so

NSNumber buttonNumber = [sender tag];

I then want to perform some methods on the corresponding image (image1). But I want to use the same method for all of the buttons.

So my question is, having retrieved the tag, how can I identify the corresponding image (with the same number after its name). The solution I have so far, which is a bit long winded, is to use a switch:

  UIImageView *image;
        switch (buttonTag) {
            case 1:
                image = imageOverButton1;
                break;
            case 2:
                image = imageOverButton2;
                break;
            default:
                break;
// etc
        }

But this doesn't seem to be very elegant. If it were a string I could of course use

stringWithFormat:@"imageOverButton%i", buttonTag

So is there an equivalent operation for objects?

I know I could also set the button's background image to the image I want and extract the imageData from the sender but I'd rather do it the above way for various reasons. I suppose I could also add the UIImageViews to an array and extract the relevant object by using the tag.

Thanks! :D

Michael

A: 

I think you answered your own question - use an array to hold your UIImageViews and use the tag as an index into that array.

EDIT, folding in my comment: The name of your objects isn't reified - you can't say NSObject foo; and then later be able to reference it with some lookup using @"foo" unless you explicitly make an array mapping names to objects. See another answer I gave to a similar problem.

Frank Shearar
Lol, ok, just thought there may be a way to retrieve an object name without having the full name but by concatenating it with another string/int/object name...
Smikey
This might help: http://stackoverflow.com/questions/2750993/name-of-uiview-that-was-touched/2751034#2751034
Frank Shearar