views:

49

answers:

1

Hi all,

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  A: 

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];
filipe
It is better to use [`copy`](http://developer.apple.com/library/ios/documentation/cocoa/conceptual/objectivec/Articles/ocProperties.html#//apple_ref/doc/uid/TP30001163-CH17-SW32) 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.
Georg Fritzsche
Brilliant - many thanks Filipe.
Ohnomycoco