11

Problem: I am doing a really big import where I parse an XML file. For every 10 parsed managed objects, I want to save the Managed Object Context and get rid of those 10 objects in memory, so that I have never more than 10 objects in memory at a time.

After saving it, how could I clear the context so that all the objects go away from memory?

dontWatchMyProfile
  • 45,440
  • 50
  • 177
  • 260

1 Answers1

26

In a situation like this there are four things to remember to do:

  1. Wrap your loop in a NSAutoreleasePool
  2. Periodically save the context; then
  3. Reset the context with -reset
  4. Release and re-create the autorelease pool

This will flush all of the memory being used and clear the context.

Marcus S. Zarra
  • 46,571
  • 9
  • 101
  • 182
  • 1
    Hey Marcus!! Aren't you the guy who wrote that big Core Data book? Thanks for the answer. Pretty sure it's the best one ;) – dontWatchMyProfile Feb 12 '10 at 20:32
  • I think we've encountered some problems these instructions don't work for. I'd love to find out different. SO User http://stackoverflow.com/users/1949877/scott-carter has a blog post http://finalize.com/2013/01/04/core-data-issues-with-memory-allocation/. Our problems are identical to the `NSTemporaryObjectID_default` section. Also cf. http://stackoverflow.com/questions/9575994. – Clay Bridges May 16 '13 at 13:03
  • The example that Scott Carter is working with in his test is poor due to use `UIManagedDocument`. `UIManagedDocument` uses a multi-moc design and releasing memory in that case is quite a bit more complicated than the straight forward situation discussed in this question. If memory management and control over the release of memory is a concern I would not use `UIManagedDocument`. In truth, I would not use it for any reason at this time as it has many documented issues. I would suggest opening a new question and sending me the link so we can work on it together. – Marcus S. Zarra May 16 '13 at 16:37