GuybrushThreepwood
GuybrushThreepwood

Reputation: 5616

Increasing number part of UIImageView variable in a for loop?

I have a three UIImageView variables called myPicture1, myPicture2 and myPicture3. In a for loop I am trying to increase the number at the end of myPicture by 1 so that I can assign a random image to each of the three variables. Here is the code below :

for (i=0; i<3; i++) {

int g = arc4random() % 19;

NSString *imagename = [NSString stringWithFormat:@"image%d.jpg",g];

UIImage *picture = [UIImage imageNamed:imagename];

 UIImageView imageView = [[UIImageView alloc] initWithImage : picture];

 self.myPicture1 = imageView; **This is where I want myPicture to increase to myPicture 2 and then 3 **

}

Is this possible ?

Thanks all,

Martin

Upvotes: 0

Views: 622

Answers (1)

filipe
filipe

Reputation: 3380

well, I think you're approaching this in a kinda awkward way.
probably the best way to do that is to have your UIImageViews stored in an NSArray. So in your class declaration, instead of

@property (nonatomic, retain) UIImageView *myPicture1;
@property (nonatomic, retain) UIImageView *myPicture2;
@property (nonatomic, retain) UIImageView *myPicture3;

you would have

@property (nonatomic, retain) NSArray *myPictures;

And then you create them like this:

NSMutableArray *myTempArray = [NSMutableArray arrayWithCapacity:3];
for (i=0; i<3; i++)
{
    int g = arc4random() % 19;

    NSString *imagename = [NSString stringWithFormat:@"image%d.jpg",g];
    UIImage *picture = [UIImage imageNamed:imagename];

    UIImageView imageView = [[UIImageView alloc] initWithImage : picture];
    [myTempArray addObject: imageView];
    [imageView release];
}
self.myPictures = [NSArray arrayWithArray: myTempArray];

Upvotes: 1

Related Questions