2016-07-07 73 views
0

多次調用我們有一個具有包含當細胞出現生成地圖快照一個UITableView的iOS應用。我們正在使用的示例列表僅僅顯示基於Model類中提供的lat/long的地圖快照。我開始注意到內存崩潰,所以我將代碼降到了最低限度。當我們只做快照而沒有對結果做任何事情時,崩潰仍然發生。見下面的代碼,它包含在我們的自定義單元格,並呼籲通過cellForItemAtIndexPath方法:MKMapSnapshotter內存崩潰 - 在一個UITableView

private func testMapSnapshot(viewModel: StreamViewModel) 
{ 
    let latDelta:CLLocationDegrees = 0.005 
    let lonDelta:CLLocationDegrees = 0.005 

    let span:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, lonDelta) 
    let location:CLLocationCoordinate2D = CLLocationCoordinate2DMake(viewModel.coordinate.latitude, viewModel.coordinate.longitude) 
    let region:MKCoordinateRegion = MKCoordinateRegionMake(location, span) 

    let options = MKMapSnapshotOptions() 
    options.region = region 
    options.size = mapImageView.frame.size 
    options.scale = UIScreen.mainScreen().scale 

    viewModel.mapSnapshotter = MKMapSnapshotter(options: options) 
    viewModel.mapSnapshotter!.startWithCompletionHandler() { snapshot, error in 
     // do nothing 
    } 
} 

didEndDisplayingCell,我要確保取消mapSnapshotter。請參閱參考(我們保持模型的列表中我們包含的tableview主VC類):

func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) 
    let model = viewModel?[indexPath.item] { 
     model.mapSnapshotter?.cancel() 
     model.mapSnapshotter = nil 
    } 
} 

注意,這樣做的最後一步之前,它被撞毀較早的方式。但是現在,如果你開始快速滾動列表,它會開始口吃,並不會停止口吃。如果你上下列出大約150行,那麼在我們開始看到內存警告,然後崩潰之前,需要不到30秒的時間。

我跑這通過儀器,但它不是非常有幫助。看起來好像堆和匿名虛擬機的分配逐漸增加,可能導致崩潰。請參閱參考:

Instruments Screenshot

我看到這個帖子在那裏: MKMapSnapshotter uses incredible amounts of CPU & RAM但它沒有答案並沒有真正解決爲什麼內存不會被釋放。

上哪兒去對這個有什麼想法?預先感謝您,請告訴我是否可以提供更多信息。

回答

1

雖然我沒能找到一個解決這個具體問題,我可以通過調用地圖snapshotter只有當停止滾動視圖來解決它 - 它然後獲取所有可見的單元格,並加載只有那些。這樣,它最大限度地減少調用該API的數量,並防止內存問題,而不是它不斷地調用它,你向下滾動通過cellForRow方法列表。

+0

MkSnapshotter是異步的。因此,無論你是快照,必須在那裏因爲它是快照 - 這可能是你的修復工程的原因。從內存角度來看,操作系統在創建對象時必須分配內存(可能原因是您看到舊代碼存在內存問題)。 Fyi,cancel()僅在實際啓動快照過程時才起作用。 – goggelj