Search code examples
objective-ccocoacore-datamemory-managementmemory-warning

Core Data Faults and Memory Warnings


Does NSManagedObject observe memory warnings and turns into a fault? Am I supposed to do this sort of stuff in tight memory situations?

Is there any guidelines on preserving memory with Core Data?


Solution

  • Core Data is designed to give you good tools to be memory friendly but much of it is not automatic. You still need to do some work.

    General guidelines are a bit tough as different situations might require some very different optimizations. That said, a few notes:

    • Not specific to Core Data but if you need to manipulate a ton of temporary objects (i.e. if inserting a bunch of data from a Web service), you might want to use @autoreleasepool{...} to ensure that those objects don't live longer than they need to.

    • Regarding binary attributes, don't load them unless you have to. Say you had a person entity that included a photo. You're better off having 'photo' be a relationship to another attribute - that means Core Data doesn't have to load that binary data each time and gives you more control over when it is brought into memory.

    • Make sure that if you're not using any of the undo functionality that you have a nil undo manager on your contexts.

    • You can use refreshObject:mergeChanges: if you have an object that you want to turn back into a fault - maybe you were only using it for a short time and you won't need it again for awhile.

    • You can set your fetch requests not to bring back any or all of an MOs property values, useful if you just need to work with a single property or something like that. You can also shoot yourself in the foot with this: if you do end up needing one of the properties you didn't pull down, Core Data has to go back to the persistent store... so make sure you're paying attention.

    Those are just a few - the 'Core Data Programming Guide' has some others and I'd say it's required reading. Overall though, just like anything else, you should do the least amount of work and then measure your usage. See how things are going and then look at optimizing the parts that need optimizing.

    Have fun!