Reputation: 3052
I noticed in instruments, that whenever I create a NSManagedObject
, at least 1 of this object stays in memory forever. I've created an empty project with 1 entity named: "Books".
The class for this entity:
class Books: NSManagedObject {
@NSManaged var name: String
convenience init(context: NSManagedObjectContext, name: String) {
let description = NSEntityDescription.entity(forEntityName: "Books", in: context)!
self.init(entity: description, insertInto: context)
self.name = name
}
deinit { print("\(type(of: self)): deinitialized") }
}
When I create several Books
, instruments shows up several instances of Books
:
When the view controller deinitializes, I clean up the context by using:
deinit {
context.registeredObjects.forEach { context.refresh($0, mergeChanges: false) }
print("\(type(of: self)): deinitialized")
}
So after the view controller has been deinitialized, instruments is still showing 1 object of Books
:
There is nothing else in the view controllers and the log is showing all the instances and controllers are deinitialized.
Question:
If I create many instances of various entities, then all of them will remain in memory forever. Is there a way to get rid of it so I can keep the memory "clean"?
Edit:
Screenshot of Visual Memory Debugger added
Upvotes: 1
Views: 325
Reputation: 70946
The short answer is that the refresh
call has nothing to do with whether an object is in memory. That code literally has no effect at all on the data you're looking at. The refresh
call, with mergeChanges:false
says that Core Data can convert the object back into a fault. It's property values and relationships may be dropped from memory, but the object itself remains.
As for why there's still a single instance in memory, it's because somewhere you have a reference to that object. The allocations tool won't help with that though. You'd be better off trying Xcode's memory graph debugger if you're concerned. I suggest though, that unless your memory situation is extremely bad, tracking down a single 64 byte allocation is probably not a high priority.
Upvotes: 2