2011-12-07 35 views
1

當我使用imageWithContentsOfFile而不是imageNamed時,UITableView滾動時出現性能問題。以下是我的代碼:iPhone:UITableView性能問題imageWithContentsOfFile

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

static NSString *CellIdentifier = @"Cell"; 
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
UniversalAppAppDelegate *delegate = (UniversalAppAppDelegate *) [[UIApplication sharedApplication] delegate]; 
NSDictionary *res = [[delegate comments] objectAtIndex:indexPath.section]; 

if (cell == nil) 
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease]; 

...... 

// This line has a problem...when I use imageNamed here instead of imageWithContentsOfFile, it works absolutely fine 
imageView = [[UIImageView alloc] initWithImage:[UIImage imageWithContentsOfFile:imagepath]]; 
[imageView setFrame: CGRectMake(30, 10, 55, 55)]; 
[sectionHeaderView addSubview:imageView]; 

...... 

cell.backgroundView = sectionHeaderView; 
return cell; 

我也曾嘗試caching圖像,但仍同樣的問題。只有imageNamed工作得很好,但我無法使用它,因爲我需要指定存儲在文檔文件夾中的圖像的路徑並動態更改。任何人都可以請告訴我如何解決這個問題?

緩存代碼:

NSMutableDictionary *thumbnailCache = [[NSMutableDictionary alloc] init]; 

- (UIImage*)thumbnailImage:(NSString*)fileName 
{ 
UIImage *thumbnail = [thumbnailCache objectForKey:fileName]; 

if (nil == thumbnail) 
{ 
    NSString *thumbnailFile = [self filePath:fileName]; 
    thumbnail = [UIImage imageWithContentsOfFile:thumbnailFile]; 
    [thumbnailCache setObject:thumbnail forKey:fileName]; 
} 
return thumbnail; 
} 

用法:

imageView = [[UIImageView alloc] initWithImage:[delegate thumbnailImage:[res objectForKey:@"ImageName"]]]; 

回答

2

你可以嘗試建立UIImages陣列控制器的viewDidLoad方法,並在cellForRowAtIndexPath使用的圖像,陣列英寸

當繪製tableview時,這將不需要爲每個圖像調用imageWithContentsOfFile

例如,您可以在單獨的線程中構建數組,並在發生這種情況時顯示加載指示符。這首先意味着一個小的加載時間,但是一個平滑的滾動tableview。

+0

這就是我所說的緩存。我已經在做,但那也沒有幫助。添加了我的緩存代碼。 – applefreak

+0

好的,謝謝你在使用緩存時在'cellForRowAtIndexPath'中做了什麼改變? – Mutix

+0

我的不好!我忘了初始化這本詞典。初始化,然後它工作正常! – applefreak