Rick
Rick

Reputation:

Using a variable in a statement to reference the image stored in a UIImageView

UPDATED Scroll down to see the question re-asked more clearly.... If I had the name of a particular UIImageView (IBOutlet) stored in a variable, how can I use it to change the image that is displayed. I tried this, but it does not work.

I'm still new to iphone programming, so any help would be appreciated.

NSString *TmpImage = @"0.png";
NSString *Tst = @"si1_1_2";

TmpImage = @"1.png";
UIImage *sampleimage = [[UIImage imageNamed:TmpImage] retain];


((UIImageView *) (Tst)).image = sampleimage;    // This is the line in question 
[sampleimage release];

RESTATED:

I have a bunch of images on the screen.... UIImageView *s1, *s2 ,*s3 etc up to *s10
Now suppose I want to update the image each displays to the same image.
Rather than doing
s1.image = sampleimage;
s2.image = sampleimage;
:
s10.image = sampleimage;

How could i write a for loop to go from 1 to 10 and then use the loop var as part of the line that updates the image.
Something like this.
for ( i = 1; i <- 10; ++i )
s(i).image = sample; // I know that does not work


Basic question is how do I incorporate the variable as part of the statement to access the image? Don't get hung up on my example. The main question is how to use a variable as part of the access to some element/object.

Bottom Line... If I can build the name of a UIImageView into a NSString object, How can I then use that NSString object to manipulate the UIImageView.

Thanks!

Upvotes: 0

Views: 370

Answers (1)

h4xxr
h4xxr

Reputation: 11465

Ugh! Your line in question:

((UIImageView *) (Tst)).image = sampleimage;

is casting a string pointer as a UIImageView pointer - you're basically saying that your pointer to a string is actually a pointer to a UIImageView! It will compile (because the compiler will accept your assertion happily) but will of course crash on running.

You need to declare a variable of type UIImageView. This can then hold whichever view you want to set the image of. So your code could look like the following:

NSString *TmpImage = @"0.png";
UIImageView *myImageView;

If (someCondition == YES) {
    myImageView = si1_1_2;  //Assuming this is the name of your UIImageView
} else {
    myImageView = si1_1_3;  //etc
}

UIImage *sampleimage = [UIImage imageNamed:TmpImage];  //no need to retain it
myImageView.image = sampleImage;

Hopefully this makes sense!

Edit: I should add, why are you trying to have multiple UIImageViews? Because a UIImageView's image can be changed at any time (and in fact can hold many), would it not be better to have merely one UIImageView and just change the image in it?

Upvotes: 1

Related Questions