开发者

Creating a method for wrapping a loaded image in a UIImageView

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)wrapImage:(NSString *)imagePath
{
  UIImage *image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle]
                                    pathForResource:imagePath 
                                             ofType:nil]];
  UIImageView *view = [[UIImageView alloc] initWithImage:image];
  view.hidden = YES;
  return view;
}

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 = [[NSM开发者_JS百科utableArray 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!


Just a note, in function declaration you should return pointer to UIImageView, not an UIImageView itself (i.e. add an asterisk).

Also, when returning the view from the function you should autorelease it. Otherwise it will leak memory. So initialization should look something like this:

UIImageView *view = [[[UIImageView alloc] initWithImage:image] autorelease];

Everything else seems to look good.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜