0

I have a for loop to go trough all relationships for a single Core Data Object, and check if the relationship has a valid image:


let context = CDStack.persitentContainer.newBackgroundContext()

let counter = 0
let object = Object.find(by: UUID, in context)

context.perform {
  for item in object.items {
     guard let item = item as? ObjectItem else {
        return
     }
     if let data = item.data {
        if UIImage(data: data) != nil {
           counter += 1
        }
     }
  }
}

The issue is that the object has thousands of items and the memory is growing too quickly. Is there a way to remove the item from context memory once I have done the necessary check and incremented my counter?

Thank you.

Astro
  • 97
  • 6
  • Usually, objects get deallocated once there are no more (strong) references to them. In your case, it could be your object is kept alive due to this. Check the memory graph tool from xcode, this should help you sort it out. – Cristik Dec 15 '22 at 19:58
  • @Cristik Is there a way to manually deallocate them? – Astro Dec 15 '22 at 21:09
  • If you manually deallocate the objects, then any other objects that reference them will have an invalid reference to those objects, which can lead to crashes and/or other unexpected behaviors. As I said, identify the strong references to the objects, and clean those up. That's the way memory management is implemented on Swift. – Cristik Dec 16 '22 at 04:17
  • Not sure why the question got market as duplicate of a reference cycle, this has nothing to do with that.... This is more a problem of memory management of bridged objective-c objects. If you wrap your UIImage(data: data) block in an autoreleasepool, it will reduce your memory issues significantly. – MartinM Dec 29 '22 at 13:44

0 Answers0