0

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

1
  • Not that you are leaking imageView if you have retain or copy properties. You should release it after invoking the property setter. Commented Sep 10, 2010 at 13:30

1 Answer 1

1

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];
Sign up to request clarification or add additional context in comments.

1 Comment

It is better to use copy for the property as NSArray is in a mutable/immutable class cluster. Then you can simply say self.myPictures = myTempArray;. Also imageView was leaked, it has to be released after adding it to the array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.