- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
Continent *continent=[self.items objectAtIndex:[indexPath row]];
ContinentCell *cell = (ContinentCell*)[tableView
dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[ContinentCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
}
cell.continentName.text=continent.continentName;
cell.textView.text=continent.countriesHash;
//cell.imageView.image=[UIImage imageWithContentsOfFile:[[NSBundle mainBundle]
pathForResource:continent.continentImage ofType:@"png"]];
cell.imageView.image = [UIImage cachedImage:continent.continentImage];
return cell;
}
我会推荐你使用 imageNamed 而不是 imageWithContentsOfFile。
imageNamed方法将图像加载到缓存中,下次它将从缓存中加载,其中 imageWithContentsOfFile 方法从您指定的路径加载图像而不进行NO缓存,它将在内存中创建多个副本。
您可以创建自己的图像缓存方法。只需声明 NSMutableDictionary *imagedCacheDict
如果内存不足,可以通过
[imagedCacheDict removeAllObjects]删除所有对象
- (UIImage*)cachedImage:(NSString*)fileName
{
UIImage *cacheImage = [imagedCacheDict objectForKey:fileName];
if (nil == cacheImage)
{
NSString *cacheImageFile = [NSString stringWithFormat:@"%@.png",
[[NSBundle mainBundle] resourcePath], fileName];
cacheImage = [UIImage imageWithContentsOfFile:cacheImageFile];
[imagedCacheDict setObject:cacheImage forKey:fileName];
}
return cacheImage;
}
所以,永远不要使用 imageNamed 方法,它会消耗大量内存来带出你的应用程序。