2014-02-16 62 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指针上的一个问题。 –