core data Refaulting

Refaulting

One way to take control of your application’s persistent data and memory use is to turn managed objects back into faults, thereby relinquishing the memory its data was occupying. You turn objects back into faults by calling the managed object context’s refreshObject:mergeChanges: method, passing the object you want to fault and NO for the mergeChanges: parameter. If, for example, I had a managed object called foo that I wanted to turn back into a fault, I would use code similar to this:

[context refreshObject:foo mergeChanges:NO];

After this call, foo is now a fault, and [foo isFault] returns YES. If you look at the code for the test we wrote previously, you’ll see a call within the loop that iterates over all movie instances to turn each movie instance back into a fault:

[context refreshObject:movie mergeChanges:NO];

Understanding the mergeChanges: parameter is important. Passing NO, as the previous code does, throws away any changed data that has not yet been saved to the persistent store. Take care when doing this because you lose all data changes in this object you’re faulting, and all the objects to which the faulted object relates are released. If any of the relationships have changed and the context is then saved, your faulted object is out of sync with its relationships, and you have created data integrity issues in your persistent store.

 

Note: Because faulting an object by calling refreshObject:mergeChanges:NO releases

relationships, you can use this to prune your object graph in memory. Faulting a movie in the

PerformanceTuning application, for example, would release its 200 related actors and 200

related studios.

Passing YES to mergeChanges: doesn’t fault the object. Instead, it reloads all the object’s persistent data from the persistent store (or the last cached state) and then reapplies any changes that existed before the call to refreshObject: that have not yet been saved.

When you turn a managed object into a fault, Core Data sends two messages to the managed object:

􏰀 willTurnIntoFault: before the object faults

􏰀 didTurnIntoFault: after the object faults

If you have implemented custom classes for your managed objects, you can implement either or both of these methods in your classes to perform some action on the object. Suppose, for example, that your custom managed object performs an expensive calculation on some persistent values and caches the result, and you want to nullify that cached result if the values it depends on aren’t present. You could nullify the calculation in didTurnIntoFault:.

posted on 2012-03-31 15:12  kiao295338444  阅读(172)  评论(0编辑  收藏  举报

导航