从图库到我的应用程序获取图像时出现内存泄漏

时间:2017-05-03 18:47:45

标签: ios swift memory-leaks phasset

我有这个功能。此功能初始化图库视图的所有媒体文件。

func initMediaFiles() {
    var assets: [PHAsset] = []
    let options = PHFetchOptions()
    options.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]

options.fetchLimit = 1000
    let results = PHAsset.fetchAssets(with: .image, options: options)
    results.enumerateObjects({ (object, _, _) in
        if let asset = object as? PHAsset {
            assets.append(asset)

        }
    })        
 SCPAsset.imageManager.startCachingImages(for: assets, targetSize: CGSize(width: 110.0, height: 147.0),contentMode: .aspectFill,  options: nil)
    for asset in assets {
        let scpAsset = SCPAsset(initWithPHAsset: asset)
        scpAsset.inspectionUUID = self.inspectionId!
        self.mediaAssets.append(scpAsset)
    }

}

每次加载图库视图时,我都无法理解为什么会出现10,000内存泄漏的原因。

1 个答案:

答案 0 :(得分:1)

这是我在一个可能有用的项目中所做的事情:

一些属性:

 let requestOptions = PHImageRequestOptions()
    let fetchOptions = PHFetchOptions()
    let cachingImageManager = PHCachingImageManager()
    var assets: [PHAsset] = [] {
        willSet {
            cachingImageManager.stopCachingImagesForAllAssets()
        }

        didSet {
            cachingImageManager.startCachingImagesForAssets(assets,
                targetSize: PHImageManagerMaximumSize,
                contentMode: .AspectFit,
                options: self.requestOptions
            )
        }
    }


    func fetchPhotos() {
        requestOptions.resizeMode = PHImageRequestOptionsResizeMode.Exact
        requestOptions.version = .Current
        requestOptions.deliveryMode = PHImageRequestOptionsDeliveryMode.HighQualityFormat
        requestOptions.synchronous = true

        fetchOptions.sortDescriptors = [NSSortDescriptor(key:"creationDate", ascending: false)]
        if #available(iOS 9.0, *) {
            fetchOptions.fetchLimit = 50
        } else {

            // Fallback on earlier versions
        }

        fetchResults = PHAsset.fetchAssetsWithMediaType(PHAssetMediaType.Image, options: fetchOptions)
        guard let fetchResults = fetchResults else {
            print("No PHAssets")
            return
        }
        dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)) { [weak self] in
            fetchResults.enumerateObjectsUsingBlock{ object, index, stop in
                let asset = object as! PHAsset
                self?.assets.append(asset)
            }
            dispatch_async(dispatch_get_main_queue()) {
                self?.photoCollectionView.reloadData()
            }
        }
    }