gpt4 book ai didi

ios - 使用 Photos 框架进行内存管理

转载 作者:行者123 更新时间:2023-11-28 08:26:05 28 4
gpt4 key购买 nike

我在从 iOS 中的照片框架检索对象时遇到内存问题。我给你看我的代码:

public class func randomImageFromLibrary(
completion: @escaping (_ error: ImageProviderError?, _ image: UIImage?, _ creationDate: Date?, _ location: CLLocation?) -> Void) {

// Create the fetch options sorting assets by creation date
let fetchOptions = PHFetchOptions.init()
fetchOptions.sortDescriptors = [ NSSortDescriptor.init(key: "creationDate", ascending: true) ]
fetchOptions.predicate = NSPredicate.init(format: "mediaType == \(PHAssetMediaType.image)")

DispatchQueue.global(qos: .userInitiated).async {

let fetchResult = PHAsset.fetchAssets(with: PHAssetMediaType.image, options: nil)

if fetchResult.count == 0 {

// The restoreAnimationAfterFetching method contains UI changes, this is why
// we perform this code on the main thread
Async.main({

print("No photos in the library!")

completion(.PhotoLibraryEmpty, nil, nil, nil)
})

return
}

var photos: [PHAsset] = []

// Enumerate the PHAssets present in the array and move everything to the photos array
fetchResult.enumerateObjects({ (object: PHAsset, index, stop: UnsafeMutablePointer<ObjCBool>) in
//let asset = object
photos.append(object)
})


let asset = photos[0] // This could be any number, 0 is only a test

// The options for the image request
// We want the HQ image, current version (edited or not), async and with the possibility to access the network
let options = PHImageRequestOptions.init()
options.deliveryMode = PHImageRequestOptionsDeliveryMode.highQualityFormat
options.version = PHImageRequestOptionsVersion.current
options.isSynchronous = false
options.isNetworkAccessAllowed = true

PHImageManager.default().requestImageData(
for: asset,
options: options,
resultHandler: { (imageData: Data?, dataUTI: String?, orientation: UIImageOrientation, info: [AnyHashable : Any]?) in

// If the image data is not nil, set it into the image view
if (imageData != nil) {

Async.main({

// Get image from the imageData
let image = UIImage.init(data: imageData!)

completion(nil, image, asset.creationDate, asset.location)
})
} else {

// TODO: Error retrieving the image. Show alert
print("There was an error retrieving the image! \n\(info![PHImageErrorKey])")

completion(.GenericError, nil, nil, nil)
}
}
)
}
}

Async是一个可以轻松管理 GCD 的框架。当我调用此方法时,我的内存负载很重。如果我多次调用它,我可以在 Instruments 中看到 PHAsset 在不释放任何东西的情况下继续增加。我想到了 autoreleasepool,但我不确定如何正确使用它。你有什么建议或类似的东西吗?最后一件事是,即使在由于内存负载过重而不断崩溃的 Today Widget 中,我也需要使用它。

最佳答案

请注意,您正在使用异步调用 requestImageData 的选项:

isSynchronous = false

您可能不需要,因为调用代码已经在后台线程中。

这也意味着结果处理程序可能会被多次调用。结合 isNetworkAccessAllowed 选项可能会延迟请求的完成和 PHAsset 实例的释放。

尝试:

isSynchronous = true
isNetworkAccessAllowed = false

关于ios - 使用 Photos 框架进行内存管理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39953714/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com