我有一个类可以获取所有用户资源,获取图像,然后对每个图像执行面部检测。我从viewDidLoad函数调用我的类,如下所示:
override func viewDidLoad() {
_ = autoreleasepool{
return faceProcessing()
}
}
这是班级:
class faceProcessing{
let manager = PHImageManager.default()
let option = PHImageRequestOptions()
init() {
let realm = try! Realm()
let assets = getAssets(realm: realm)
option.isSynchronous = true
option.deliveryMode = .fastFormat
option.isNetworkAccessAllowed = true
var featuresCount = 0
for assetIndex in 0...assets.count-1{
featuresCount += autoreleasepool{() -> Int? in
print(assetIndex)
var facesCount = 0
faceDetection(asset: assets[assetIndex]) { (features) in
facesCount = features
}
return facesCount
}!
}
print(featuresCount)
}
func getAssets(realm: Realm)->[PHAsset]{
return autoreleasepool{ () -> [PHAsset] in
let images = realm.objects(Image.self).filter("asset != nil")
let ids: [String] = images.map {$0.id}
let options = PHFetchOptions()
options.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]
let assets = PHAsset.fetchAssets(withLocalIdentifiers: ids, options: options)
var assetArray = [PHAsset]()
if(assets.count > 1){
for assetIndex in 0...assets.count-1{
assetArray.append(assets[assetIndex])
}
}
return assetArray
}
}
func faceDetection(asset: PHAsset, completionHandler:@escaping (Int)->Void){
manager.requestImageData(for: asset, options: option){
(data, responseString, imageOriet, info) in
if (data != nil){
weak var faceDetector = CIDetector(ofType: CIDetectorTypeFace, context: nil, options: [CIDetectorAccuracy: CIDetectorAccuracyHigh])
let faces = (faceDetector?.features(in: CIImage(data: data!)!))
faceDetector = nil
completionHandler((faces?.count)!)
}else{
print(info)
}
}
}
}
问题是在完成获取图像和检测面部的过程后,内存将不会释放。在此过程之前,内存大约为60MB,在此过程中,内存大小在400MB到500MB之间,当过程完成时,内存大约为300MB。是否有一种方法可以释放整个内存,并在完成该过程后有60MB?
以下是仪器的外观:
看起来人脸检测没有释放内存,所以有一种方法可以从内存中释放CIDetection吗?