Saving images to core data runs of memory

I'm trying to do a mass conversion of images to data so it can be stored in core data. The conversion part works fine, and if I do it without updating core data it shows memory usage at less that 100MB

If I update the core data object, it just keeps consuming memory until the app crashes.

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")
    }
}

If I comment out the picture.pictureData = imageData line I don't get the memory issues. What's the correct way of going about this? There is an unknown number of images (mine current sits at about 5.5GB worth, 800+)

Replies

Does this solve your question?

https://codermite.com/t/core-data-memory-consumption-is-too-high-ios-uikit/243

  • not sure who posted that but they’ve literally just taken my post and changed a few variable names.

    I have actually been playing around with the second idea, but it’s an absolute pain having to erase and restore backup each time it fails as downloading & restoring the app container doesn’t work

  • Are you talking about the second idea of the answer posted in that site? In that case, if you have any question related to that, you can post a question/reply in that site if you want to.

Add a Comment