2011-09-09 74 views
1

我有一個圖像緩存類,它將配置文件圖像存儲在NSMutableDictionary中。如果密鑰存在,則緩存返回UIImage對象,如果不存在,則下載它,將其存儲在字典中,並返回UIImage。這種共享緩存被稱爲NSThreaded方法中是這樣的:UITableViewCell線程中的圖像緩存

[NSThread detachNewThreadSelector:@selector(setImageForUser:) toTarget:self withObject:imageUrlString]; 

-(void)setImageForUser:(NSString *)imageUrlString { 
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 

    LPImageCacher *imageCache = [LPImageCacher sharedCache]; 
    UIImage *profileImg = [imageCache getCachedImageFromMemory:imageUrlString]; 
    self.userProfileImageView.image = profileImg; 
    if (profileImg == nil) { 
     imageUrlString = [[myGlobals sharedInstance].avatarUrlDefault stringByAppendingString:@"/avatar.png"]; 
     self.userProfileImageView.image = [imageCache getCachedImageFromMemory:imageUrlString]; 
    } 

    [pool release]; 
} 

的問題是,如果他們滾動的UITableView加載任何東西之前,圖像獲得積壓,然後最終所有的圖像加載它們閃爍或改變在當前的單元格上,直到它到達正確的單元格。我認爲在每個單元格中創建一個NSThread實例並且僅僅取消-prepareForReuse中的線程會很好,但我似乎無法再次重用NSThread對象,關於如何解決這個問題的任何想法?

回答

0

裏德奧爾森給了你直接的答案。我想提到另一件事。

爲每個單元調度線程相當昂貴,爲什麼不使用NSOperationQueue?您可以擁有一組工作線程來完成每個單獨的加載,並且將該隊列的功能限制在任何時候最大可見單元的數量是有意義的。這幾乎是「重用線程」。

事實上,我會建議使用ASIHTTP的ASINetworkQueue。它比NSOperationQueue更簡單。

此外,嘗試添加一個簡單的優化來加載單元格,一旦滾動速度低於某個數字。爲什麼打擾加載圖像,當你無法停下來看到他們?舉例來說,我寫的是這樣的一個的tableView:

- (void)scrollViewDidScroll:(UIScrollView *)scrollView 
{ 
    static float prevOffset = 0.0; 
    static float scrollSpeed = 0.0; 

    // positive -> downwards 
    scrollSpeed = scrollView.contentOffset.y - prevOffset; 

    if (scrollSpeed < 2.0) 
    { 
     [self loadImagesForVisibleCellsInTableView:(UITableView*)scrollView]; 
    } 
    else if (scrollSpeed < 6.0) 
    { 
     shouldLoadImages = YES; 
    } 
    else 
    { 
     shouldLoadImages = NO; 
    } 

    prevOffset = scrollView.contentOffset.y; 
} 

這忽略加載新的圖像時的tableView快速移動(shouldLoadImages影響tableView:cellForRowAtIndexPath,告訴他們忽略裝載圖像)時,它的即將停止,它強制重新加載可見單元格。