【发布时间】:2016-05-18 19:28:36
【问题描述】:
您好,我正在使用 MKMapSnapshotter 生成地图图像并使用 SDWebImage 缓存它们。地图图像将显示在每个 uitableview 单元格中。
我遇到的问题是对于大约 30 个 uitableview 单元,使用的内存为 130 MB,如果我不使用地图图像,则使用的内存为 25 MB,最后使用地图图像但没有缓存(如生成每次显示单元格时映射图像)使用的内存为 50 MB。
如何减少内存使用?或者我如何存储图像以减少它们占用的内存空间?任何帮助,将不胜感激。 我的代码如下。
全班第一:
var imageCache: SDImageCache!
var mySnapOptions: MKMapSnapshotOptions!
let regionRadius: CLLocationDistance = 300
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)
在 viewDidLoad() 中:
imageCache = SDImageCache(namespace: "myNamespace")
mySnapOptions = MKMapSnapshotOptions()
mySnapOptions.scale = UIScreen.mainScreen().scale
在 cellForRow 中:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject?) -> TableViewCell? {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! TableViewCell
if let post = object {
cell.mapImageView.image = UIImage(named: "MapPlaceholder")
let tempLoc = post["location"] as! PFGeoPoint
let loc = CLLocation(latitude: tempLoc.latitude, longitude: tempLoc.longitude)
imageCache.queryDiskCacheForKey(post.objectId, done: {(image: UIImage?, cacheType: SDImageCacheType!) in
if let cachedImage = image {
cell.mapImageView.image = cachedImage
}else {
cell.mapPinImageView.hidden = true
cell.mapActivityIndicator.startAnimating()
dispatch_async(self.queue) { () -> Void in
self.mySnapOptions.region = MKCoordinateRegionMakeWithDistance(loc.coordinate,
self.regionRadius * 2.0, self.regionRadius * 2.0)
self.mySnapOptions.size = (cell.mapImageView.image?.size)!
MKMapSnapshotter(options: self.mySnapOptions).startWithCompletionHandler { snapshot, error in
guard let snapshot = snapshot else {
print("Snapshot error: \(error)")
return
}
self.imageCache.storeImage(snapshot.image, forKey: post.objectId, toDisk: true)
dispatch_async(dispatch_get_main_queue(), {
cell.mapActivityIndicator.stopAnimating()
cell.mapImageView.image = snapshot.image
cell.mapPinImageView.hidden = false
})
}
//
}
}
})
}
return cell
}
【问题讨论】:
-
我会调低比例,看看是否有帮助
-
@DavidYangLiu 将规模从 3 倍减少到 2 倍确实会稍微提高内存使用率,从 130 MB 到 85 MB。但是图像没有那么清晰。我认为这不是一个理想的解决方案,但感谢您的建议。
-
是的,别以为你可以一边吃蛋糕一边吃它。要么你因为把所有这些都记在内存中而受到打击,要么你减少了图像的分辨率。或者最后一件事是使图像的加载异步并在加载完成后将其呈现在屏幕上。但如果使用滚动通过单元格,则取消所有正在进行的工作。这样您就不必缓存图像,但您可能会在滚动时遇到空图像,然后再填充
-
理想情况下,我想将它们存储在内存中,从我读到的存储在内存中的图像是 width*height*4 。当您有很多图像时,它会使用大量内存。重图像的现代应用程序是如何做这种事情的?
-
我真的不明白人们如何使用 MapKit 框架......也许我太愚蠢了。我从一个集合视图单元格中的
MKMapView开始,这导致了主要的内存问题(释放后没有内存清理)。然后我切换到MKMapSnapshotter,这已经是一个权衡,因为地图部分是非交互式的。但即使是这种解决方案,也会导致每个单元的内存增加 5mb,最终下降到 80mb(从 120mb)。图像本身为 144kb。为什么加载的切片缓存如此激进?
标签: ios iphone uitableview memory uiimage