您的位置:首页 > 其它

Core Data Memory Management - Reducing Memory Overhead

2014-12-22 20:39 393 查看
使用Core Data 中经常遇到的一个很重要的问题就是内存问题,因此需要很谨慎地考虑内存问题,否则在工程规模比较大或者操作大量数据的时候就显得尤为重要,下面是Apple官方文档的说明。

OverView
It is sometimes the case that you want to use managed objects on a temporary basis, for example to calculate an average value for a particular attribute. This causes your object graph, and memory consumption, to grow. You can reduce the memory overhead by re-faulting individual managed objects that you no longer need, or you can reset a managed object context to clear an entire object graph. You can also use patterns that apply to Cocoa programming in general.

1、You can re-fault an individual managed object using NSManagedObjectContext's refreshObject:mergeChanges: method. This has the effect of clearing its in-memory property values thereby reducing its memory overhead. (Note that this is the same as setting the property values to nil - the values will be retrieved on demand if the fault is fired).

2、When you create a fetch request you can set includesPropertyValues to NO to reduce memory overhead by avoiding creation of objects to represent the property values. You should typically only do so, however, if you are sure that either you will not need the actual property data or you already have the information in the row cache, otherwise you will incur multiple trips to the persistent store.

3、You can use the reset method of NSManagedObjectContext to remove all managed objects associated with a context and "start over" as if you'd just created it. Note that any managed object associated with that context will be invalidated, and so you will need to discard any referenes to and re-fetch any objects associated with that context in which you are still interested.

4、If you iterate over a lot of objects, you may need to use local autorelease pool blocks to ensure temporary objects are deallocated as soon as possible.

5、If you do not intend to use Core Data's undo functionality, you can reduce your application's resource requirements by setting the context's undo manager to nil. This may be especially beneficial for background worker threads, as well as for large import or batch operations.

6、Finally, Core Data does not by default keep strong references to managed objects (unless they have unsaved changes). If you have lots of objects in memory, you should determine the owning references. Managed objects maintain strong references to each other through relationships, which can easily create strong reference cycles. You can break cycles by re-faulting objects (again by using the refreshObject:mergeChanges: method of NSManagedObjectContext).
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  individual particular