2010-06-06 83 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]; 

其他一切看起來都不錯。