Core Data Memory Management

前端 未结 2 1381
鱼传尺愫
鱼传尺愫 2021-02-04 14:08

I\'ve read the memory management sections in the Core Data docs and I\'m still a little confused. I have one context in my app, and I have several things getting objects out of

相关标签:
2条回答
  • 2021-02-04 14:42

    Yes, CoreData will fault things back that you are not using. It has caches and various other things, so the data might not be released immediately, but in general it is very good about memory management and dealing with keeping its footprint as small as possible.

    If you have a particularly odd usage profile you can explicitly force objects back into faults, but that is generally not necessary, and I would not consider doing that unless I actually had some actual profiling data saying I was under memory pressure.

    0 讨论(0)
  • 2021-02-04 14:43

    Core Data manages object lifetimes the same way the rest of Cocoa manages object lifetimes: NSManagedObject instances in a managed object context are retained in memory as long as the managed object context or any other object retains ownership of them (via -[NSObject retain]. By default, the NSManagedObjectContext does not retain instances, so they are released as soon as any other owners (i.e. your NSFetchedResultsController instances or other instances in your program) release them. You can change this default behavior of the managed object context to retain instances, but you rarely want to. The managed object context has to retain instances that are updated until the next save. There's no way to preserve these changes except in the object instance until the context is saved. So, to minimize memory usage of Core Data objects, follow the standard rules: release them as soon as you can. If you find that your context memory usage is growing (use Instruments' Core Data instruments to track this), save the context more frequently if you are updating instances and hence keeping them alive in the context until the next save even if you've otherwise released them.

    Using NSFetchedResultsController makes all of this easier. In fact, the reason NSFetchedResultsController exists at all is to make batch fetching in a low memory environment (like the iPhone) easier for the programmer.

    As Louis mentioned, the NSPersistentStoreCoordinator maintains a row cache to cache instance data in memory instead of having to go back to disk when an object is faulted into the managed object context. This is a Core Data implementation detail, however (though cache misses are a performance hit; you can track cache misses in Instruments). Core Data manages the cache memory and you shouldn't have to worry about it.

    0 讨论(0)
提交回复
热议问题