我有这个简单的UITableView,每个单元格都有一个与之对应的图像。我正在做的就是在每个单元格中显示图像的标题和图像本身。这是我的cellForRowAtIndexPath:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// this is where the data for each cell is
NSDictionary *dataForThisCell = cachedData.posts[indexPath.row][@"data"];
// this creates a new cell or grabs a recycled one, I put NSLogs in the if statement to make sure they are being recycled, they are.
post *cell = (post *) [self.tableView dequeueReusableCellWithIdentifier:@"postWithImage"];
if (cell == nil) {
cell = [[[NSBundle mainBundle]loadNibNamed:@"postWithImage" owner:self options:nil]objectAtIndex:0];
[cell styleCell];
}
// if this cell has an image we need to stick it in the cell
NSString *lowerCaseURL = [dataForThisCell[@"url"] lowercaseString];
if([lowerCaseURL hasSuffix: @"gif"] || [lowerCaseURL hasSuffix: @"bmp"] || [lowerCaseURL hasSuffix: @"jpg"] || [lowerCaseURL hasSuffix: @"png"] || [lowerCaseURL hasSuffix: @"jpeg"]) {
// if this cell doesnt have an UIImageView, add one to it. Cells are recycled so this only runs several times
if(cell.preview == nil) {
cell.preview = [[UIImageView alloc] init];
[cell.contentView addSubview: cell.preview];
}
// self.images is an NSMutableDictionary that stores the width and height of images corresponding to cells.
// if we dont know the width and height for this cell's image yet then we need to know now to store it
// once the image downloads, and then cause our table to reload so that heightForRowAtIndexPath
// resizes this cell correctly
Boolean shouldReloadData = self.images[dataForThisCell[@"name"]] == nil ? YES : NO;
// download image
[cell.preview cancelImageRequestOperation];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString: dataForThisCell[@"url"]]];
[request addValue:@"image/*" forHTTPHeaderField:@"Accept"];
[cell.preview setImageWithURLRequest: request
placeholderImage: [UIImage imageNamed:@"thumbnailLoading.png"]
success: ^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
// if we indicated earlier that we didnt know the dimensions of this image until
// just now after its been downloaded, then store the image dimensions in self.images
// and tell the table to reload so that heightForRowAtIndexPath
// resizes this cell correctly
if(shouldReloadData) {
NSInteger imageWidth = image.size.width;
NSInteger imageHeight = image.size.height;
if(imageWidth > [ColumnController columnWidth]) {
float ratio = [ColumnController columnWidth] / imageWidth;
imageWidth = ratio * imageWidth;
imageHeight = ratio* imageHeight;
}
if(imageHeight > 1024) {
float ratio = 1024 / imageHeight;
imageHeight = ratio * imageHeight;
imageWidth = ratio* imageWidth;
}
self.images[dataForThisCell[@"name"]] = @{ @"width": @(imageWidth), @"height": @(imageHeight), @"titleHeight": @([post heightOfGivenText: dataForThisCell[@"title"]]) };
[self.tableView reloadData];
// otherwise we alreaady knew the dimensions of this image so we can assume
// that heightForRowAtIndexPath has already calculated the correct height
// for this cell
}else{
// assign the image we downloaded to the UIImageView within the cell
cell.preview.image = image;
// position the image
NSInteger width = [self.images[dataForThisCell[@"name"]][@"width"] integerValue];
NSInteger height = [self.images[dataForThisCell[@"name"]][@"height"] integerValue];
cell.preview.frame = CGRectMake( ([ColumnController columnWidth] - width)/2 , [self.images[dataForThisCell[@"name"]][@"titleHeight"] integerValue] + 10, width, height);
}
}
failure: ^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {}];
}
// set title of the cell
cell.title.text = [NSString stringWithFormat: @"%@\n\n\n\n\n", dataForThisCell[@"title"]];
`enter code here`// ask for a restyle
[cell setNeedsLayout];
// returns my customized cell
return cell;
}
所发生的事情是,一切都按照我想要的方式运行,但是一旦我向下滚动大约100个单元格左右,我的应用程序的背景变黑了几秒钟,然后我看到我的主屏幕(我看到了一些人们称之为HSOD - 死亡的主屏幕)。有时在xcode的控制台中,我会在崩溃前看到内存警告,有时候我没有。
我知道无论问题是什么,它都与将图像放入细胞有关。如果我注释掉这一行:
cell.preview.image = image;
然后一切正常,它不会再崩溃(但当然图像不会在单元格中显示)。
正在重复使用这些单元格,我知道这样做有效,我将UIImageView的图像属性设置为nil:
- (void) prepareForReuse {
[super prepareForReuse];
if(self.preview != nil)
self.preview.image = nil;
}
在我的appDelegate中我也定义了这个:
- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
[UIImageView clearAFImageCache];
}
哪个删除了图像缓存,但也没有解决问题(无论如何iOS都应该自动清除图像缓存内存警告)。
我对我的项目进行了分析,并且报告没有内存泄漏,这里是分析器显示,以及显示崩溃时的分配:
除了控制台中偶尔出现的内存警告大约是应用程序崩溃时间的2/3时,控制台中没有其他错误,我也没有遇到任何断点或异常。
答案 0 :(得分:2)
所有这些分配都是您在每次请求时创建新的表格视图单元格,而不是重用现有的单元格视图单元格。如果没有为reuseIdentifier
创建的单元格设置UINib
,dequeueReusableCellWithIdentifier:
将始终返回`nil。
要解决此问题,请添加以下代码(引用为in this question):
[self.tableView registerNib:[UINib nibWithNibName:@"nibname"
bundle:nil]
forCellReuseIdentifier:@"cellIdentifier"];
答案 1 :(得分:0)
我找到了一个解决方案,虽然不是一个完美的解决方案:
AFNetworking库很棒,我认为我的问题的原因在于我自己的代码或者我对NSCache的工作方式缺乏了解。
AFNetworking使用Apple的NSCache缓存图像。 NSCache类似于NSMutableDictionary,但在内存稀疏时释放对象(参见更多here)。
在UIImageView + AFNetworking.m中,我找到了
的定义+ (AFImageCache *)af_sharedImageCache
将其改为类似于:
+ (AFImageCache *)af_sharedImageCache {
static AFImageCache *_af_imageCache = nil;
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
_af_imageCache = [[AFImageCache alloc] init];
_af_imageCache.countLimit = 35;
});
return _af_imageCache;
}
这里重要的一行是
_af_imageCache.countLimit = 35;
这告诉AFNetworking中使用的NSCache对象缓存图像,它必须最多只能缓存35件事。
由于我不知道的原因,iOS不会自动从缓存中清除对象,并且在缓存上调用removeAllObjects也不起作用。这个解决方案并不理想,因为它可能不会充分利用缓存或者可能过度使用缓存,但同时它至少会阻止缓存尝试存储无限数量的对象。