2014-02-16 63 views
1

存儲NSOperationQueues時,我有一個加載縮略圖進入細胞aynchronously如下一個UITableView內存崩潰的NSCache

NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock: 
^{ 
    ThumbnailButtonView *thumbnailButtonView = [tableViewCell.contentView.subviews objectAtIndex:i]; 
    UIImage *image = [self imageAtIndex:startingThumbnailIndex + i]; 
    [self.thumbnailsCache setObject: image forKey:[NSNumber numberWithInt:startingThumbnailIndex + i]]; 

    [[NSOperationQueue mainQueue] addOperationWithBlock: 
    ^{ 
     UITableViewCell *tableViewCell = [self cellForRowAtIndexPath:indexPath]; 
     if (tableViewCell) 
     { 
      [activityIndicatorView stopAnimating]; 
      [self setThumbnailButtonView:thumbnailButtonView withImage:image]; 
     } 

    }]; 
}]; 

[self.operationQueue addOperation:operation]; 
[self.operationQueues setObject:operation forKey:[NSNumber numberWithInt:startingThumbnailIndex + i]]; 

由於每一個技術我在WWDC演講學會,存着我所有的操作隊列中一個NSCache稱爲operationQueues因此以後我可以取消他們,如果小區滾出屏幕(也有在小區3頁的縮略圖):

- (void) tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    NSInteger startingThumbnailIndex = [indexPath row] * self.thumbnailsPerCell; 

    for (int i = 0; i < 3; i++) 
    { 
     NSNumber *key = [[NSNumber alloc] initWithInt:i + startingThumbnailIndex]; 
     NSOperation *operation = [self.operationQueues objectForKey:key]; 

     if (operation) 
     { 
      [operation cancel]; 
      [self.operationQueues removeObjectForKey:key]; 
     } 
    } 

} 

然而,我發現,如果我反覆啓動,負載,然後閉上UITableView,我開始接收內存警告,然後最終該應用程序崩潰。當我刪除此行時:

[self.operationQueues setObject:operation forKey:[NSNumber numberWithInt:startingThumbnailIndex + i]]; 

內存問題消失。有沒有人有任何線索爲什麼將操作隊列存儲在緩存或數組中會導致應用程序崩潰?

回答

0

注意:前兩天我瞭解了NSCacheNSOperationQueue,所以我可能是錯的。

我不認爲這是NSOperationQueue的問題,您將圖片添加到您的thumbnailsCache,但是當視圖在屏幕外滾動時,它們仍在內存中。我猜測,當單元格向後滾動時,您會重新創建圖像。這可能會阻礙你的記憶。

此外,你不應該緩存你的圖像,而不是你的操作?

編輯

我,直到我的應用程序崩潰添加圖像和字符串做了與NSCache一些詳細的測試。它似乎沒有驅逐任何項目,所以我寫了我的自定義緩存,這似乎工作:

@implementation MemoryManagedCache : NSCache 

- (id)init 
{ 
    self = [super init]; 

    if (self) { 
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reduceMemoryFootprint) name:UIApplicationDidReceiveMemoryWarningNotification object:nil]; 
    } 

    return self; 
} 

- (void)reduceMemoryFootprint 
{ 
    [self setCountLimit:self.countLimit/2]; 
} 

@end 
+0

我緩存縮略圖緩存中的圖像。我不認爲這是重新創建堵塞內存的圖像,因爲如果我刪除上面提到的這一行,它可以正常工作。無論出於何種原因,它都必須將NSOperationQueues存儲在數據結構中。感謝您的迴應 - 這是一個奇怪的問題,可能是一個蘋果錯誤。 –

+0

你可能是對的。 [其他人](http://www.photosmithapp.com/index.php/2013/10/photosmith-3-0-2-photo-caching-and-ios-7/)也有'NSCache'問題。 – Pranav

+0

我甚至不確定它是NSCache,因爲我也嘗試過使用NSMutableArray並得到相同的結果。我認爲這只是懸掛在NSOperationQueues指針上的一個問題。 –