Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I clear the Managed Object Context?

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?

like image 440
dontWatchMyProfile Avatar asked Feb 12 '10 14:02

dontWatchMyProfile


People also ask

What is the purpose of managed object context?

A managed object context is an instance of NSManagedObjectContext . Its primary responsibility is to manage a collection of managed objects. These managed objects represent an internally consistent view of one or more persistent stores.

Will you ever pass managed object from one context to another context?

You cannot pass NSManagedObjects between multiple contexts, but you can pass NSManagedObjectIDs and use them to query the appropriate context for the object represented by that ID.

Can we have more than one managed object context?

Most apps need just a single managed object context. The default configuration in most Core Data apps is a single managed object context associated with the main queue. Multiple managed object contexts make your apps harder to debug; it's not something you'd use in every app, in every situation.

Is managed object context thread safe?

The NSManagedObjectContext class isn't thread safe. Plain and simple. You should never share managed object contexts between threads. This is a hard rule you shouldn't break.


1 Answers

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.

like image 127
Marcus S. Zarra Avatar answered Oct 12 '22 21:10

Marcus S. Zarra