2010-06-06 82 views
0

包裹加载图像的方法,我有以下联合国我的applicationDidFinishLaunching方法创建在一个UIImageView

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

我只是添加图片到视图。但是因为我需要添加30-40张图片,所以我需要将上述内容包装在一个函数中(它返回一个UIImageView),然后从循环中调用它。

这是我创造的功能

-(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; 
} 

然后调用它,我已在迄今以下,为简单起见,我只包装3个图像

//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]; 

我有2个第一次尝试一般问题

  1. 我的方法是否正确?即,遵循最佳实践,对于我(加载多个图像(jpg,png等)并将它们添加到容器视图中)
  2. 为了使此功能可以与大量图像正常使用,是否需要保留我的数组创建与我的方法调用分开吗?

欢迎任何其他建议!

回答

0

只需要注意,在函数声明中,您应该返回指向UIImageView的指针,而不是UIImageView本身(即添加星号)。

另外,从函数返回视图时,应该自动释放它。否则会泄漏内存。所以初始化应该看起来像这样:

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

其他一切看起来都不错。