Creating a method for wrapping a loaded image in a UIImageView

Posted by eco_bach on Stack Overflow See other posts from Stack Overflow or by eco_bach
Published on 2010-06-06T18:47:37Z Indexed on 2010/06/06 18:52 UTC
Read the original article Hit count: 244

I have the following un my applicationDidFinishLaunching method

UIImage *image2 = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"image2.jpg" ofType:nil]];
view2 = [[UIImageView alloc] initWithImage:image2];
view2.hidden = YES;
[containerView addSubview:view2];

I'm simply adding an image to a view. But because I need to add 30-40 images I need to wrap the above in a function (which returns a UIImageView) and then call it from a loop.

This is my first attempt at creating the function

-(UIImageView)wrapImageInView:(NSString *)imagePath
{
UIImage *image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:imagePath      
ofType:nil]];
UIImageView *view = [[UIImageView alloc] initWithImage:image];
view.hidden = YES;
}

And then to invoke it I have the following so far, for simplicity I am only wrapping 3 images

//Create an array and add elements to it
NSMutableArray *anArray = [[NSMutableArray alloc] init];
[anArray addObject:@"image1.jpg"];
[anArray addObject:@"image2.jpg"];
[anArray addObject:@"image3.jpg"];

//Use a for each loop to iterate through the array
for (NSString *s in anArray) {
UIImageView *wrappedImgInView=[self wrapImage:s];
[containerView addSubview:wrappedImgInView];
 NSLog(s);
}
//Release the array
[anArray release];

I have 2 general questions
1-Is my approach correct?, ie following best practices, for what I am trying to do (load a multiple number of images(jpgs, pngs, etc.) and adding them to a container view)
2-For this to work properly with a large number of images, do I need to keep my array creation separate from my method invocation?

Any other suggestions welcome!

© Stack Overflow or respective owner

Related posts about objective-c

Related posts about best-practices