我正在尝试将图像大规模转换为数据,以便将其存储在核心数据中。 转换部分工作正常,如果我在不更新核心数据的情况下进行转换,它会显示内存使用量小于 100MB
如果我更新核心数据对象,它只会继续消耗内存,直到应用程序崩溃。
func updateLocalImages() {
let fetchRequest: NSFetchRequest<Picture> = Picture.fetchRequest()
fetchRequest.predicate = NSPredicate(format: "pictureName != \"\"")
do {
let pictures = try moc.fetch(fetchRequest)
print("Picture Update Count: \(pictures.count)")
for picture in pictures {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let path = paths[0]
if let picName = picture.pictureName {
let imagePath = path.appendingPathComponent(picName)
if let uiImage = UIImage(contentsOfFile: imagePath.path) {
if let imageData = uiImage.jpegData(compressionQuality: 1.0) {
autoreleasepool {
picture.pictureData = imageData
print("Picture Updated")
saveContext()
}
}
}
}
}
} catch {
print("Fetching Failed")
}
}
如果我注释掉 picture.pictureData = imageData 行,我就不会遇到内存问题。
正确的做法是什么?图片数量未知(我目前的大小约为 5.5GB)
发现问题是核心数据似乎没有释放对象。我改成下面的了
if let pictures = project.pictures {
projectPicNumber = pictures.count
for pic in pictures {
currentPicNumber = currentPicNumber + 1
let picture : Picture = pic as! Picture
if let imgData = convertImage(picture: picture) {
picture.pictureData = imgData
}
}
project.converted = true
saveContext()
viewContext.refreshAllObjects()
}
转换33张图片时最多占用内存约500MB