我正在使用下面的代码将图像转换为数据,并将其存储在核心数据中,但是由于内存耗尽,导致应用程序崩溃。该应用程序也被冻结,直到代码完成。
DispatchQueue.main.async {
let fetchRequest: NSFetchRequest<Project> = Project.fetchRequest()
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]
do {
let results = try self.appData.moc.fetch(fetchRequest)
let fileManager = FileManager.default
for project in results {
NSLog("Project Name: \(String(describing: project.name))")
if let mainPic = project.mainPicture {
if let mainPicName = mainPic.pictureName {
let imagePath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent(mainPicName)
if fileManager.fileExists(atPath: imagePath) {
if let image : UIImage = UIImage(contentsOfFile: imagePath) {
let imageData = image.pngData()
}
}
}
}
}
} catch {
print("Fetching Failed")
}
self.appData.saveContext()
NSLog("13 Ran")
}
如果我注释掉let imageData = image.pngData()这一行,那么我就不会出现这个问题了
如果注释掉这一行,应用程序加载后的内存使用量小于100MB,如果不注释,则会达到1.15GB,然后回到150MB左右。
我想这是一个内存问题。
取了多少个项目?
而且你可以把代码改成。
DispatchQueue.main.async {
let fetchRequest: NSFetchRequest<Project> = Project.fetchRequest()
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]
do {
let results = try self.appData.moc.fetch(fetchRequest)
let fileManager = FileManager.default
for project in results {
autoreleasepool {
NSLog("Project Name: \(String(describing: project.name))")
if let mainPic = project.mainPicture {
if let mainPicName = mainPic.pictureName {
let imagePath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent(mainPicName)
if fileManager.fileExists(atPath: imagePath) {
if let image : UIImage = UIImage(contentsOfFile: imagePath) {
let imageData = image.pngData()
}
}
}
}
}
}
} catch {
print("Fetching Failed")
}
self.appData.saveContext()
NSLog("13 Ran")
}
我想应该没问题