Passing objects between managed object contexts - iphone

I have an iphone app with 2 managed object contexts. One of my contexts deals with a picker, which allows the user to add new records and then select one of those new records. Once the picker is hidden, that managed object context is saved and discarded.
I then want to use this selected object in my second managed object context, and add (relate) it to another object. This second MOC's changes may be saved or deleted. This is why the first MOC is created to allow the changes made in the picker to always be saved no matter wether they save or discard the changes in the second MOC.
I hope this is clear! My problem is that when the user selects the object from the picker, this object resides in a different context to where it needs to be used. Is there a way you can pass objects between contexts? Perhaps using the object's ID (after it has been persisted).
Thanks for your help!

You mentioned the correct solution in the question. 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. So simply persist out the data (via a save:), and then pass the ID to the other context and use it to ask the context for the appropriate object.
Depending on what you want to do you may want to rig up the mergeChangesFromContextDidSaveNotification: so that changes in one context are automatically reflected in the other.

Related

Walk tree of objects for change detection

TL;DR: Can EFCore do some kind of DetectChanges(someEntity) and automatically walk the object tree from that entity?
My domain model is created in Domain Driven Design style, where object references are only within an aggregate (e.g. PurchaseOrder.Lines is a collection of PurchaseOrderLine) and associations outside of the aggregate are by Id only (e.g. PurchaseOrder.CustomerId is a Guid, instead of a property to a Customer object).
I am retrieving many objects from the DB and altering them. At the end of the process I want to decide which objects to save and which ones not to. So, I want to only save modified objects that I specifically state have changed via PurchaseOrderRepository.Update(purchaseOrder), but I also want to ensure all related objects are checked for changes too (so I'd like EFCore to see that 2 objects were removed from purchaseOrder.Lines so should be deleted, and 1 new one was added).
I don't want to automatically save everything that is retrieved + modified, only what I explicitly state should be. Is this something that is possible?
For example:
If I load a lot of objects, modify them, and then they fail my domain validation, I want to abandon saving changes to those objects and instead save a new Event of some kind in the DB saying a file import failed.

How does refreshObject work in nested managed object contexts?

Say I have an object on a parent, main queue concurrency type, and I change one of its property values. Then, without saving, I execute a fetch request on a child, private queue type, to fetch an array where that object is included. The issue I'm having is that sometimes the object I get does not have the pending changes included that were made on the main thread, although it should.
However, if I call [childMOC refreshObject:object mergeChanges:YES];, I do get pending changes. But the description in the documentation says that this method
"Updates the persistent properties of a managed object to use the
latest values from the persistent store.
" Wouldn't these values then be the values that are saved to disk, so it would not include any pending changes?
I'm a little confused as to how this method works..
With nested managed object contexts, child context will not see any changes made directly to the parent context. You will always need to refresh your object in child context if you want the latest changes.
And yes, refreshing includes pending changes from the parent context. The docs need update in that regard.
The change propagation goes automatically (when saving) only from child -> parent context.

Why does updating an object only work one, particular way?

I am trying to update an object using EF4. An object is passed from the strongly-typed page to the action method and
[HttpPost]
public ActionResult Index(Scenario scenario, Person person)
{
// Some business logic.
// Update Scenario with Person information.
scenario.Person = person;
// Update the corresponding object and persist the changes.
// Note that the repository stems from the repository pattern. Contains the ObjectContext.
Scenario updateScenario = repository.GetScenario(scenario.ScenarioID);
updateScenario = scenario;
repository.Save();
}
However, the problem is that the changes do not persist when I do this. However, if I instead update every single property within the scenario individually and then persist the changes (via the Save method), everything is persisted.
I'm confused why this is happening. In my real application, there are MANY items and subobjects within a Scenario so it is not feasible to update every individual property. Can someone please help clear up what is happening and what I need to do to fix it?
In the context of your action method, you have two different objects of type Scenario. scenario points to one of the objects and updateScenario points to another one. With the line of code:
updateScenario = scenario
All you are doing is causing the updateScenario to point to the same object that scenario points to, you are not copying the values that make up the object from one to another. Essentially, your database context is aware of only 1 of the 2 instances of Scenario. The other instance of Scenario was created outside of the context and the context has not been made aware of it.
In your particular scenario you can accomplish what you want by not taking a Scenario on your parameter, and instead, pull the Scenario that you want to update from your database context and in your action method, invoke:
this.TryUpdateModel(updateScenario);
This will cause the model binder to update the property/fields on the Scenario object that your database context is aware of, and therefore will persist the changes when you call Save().
HTH

Create a Core Date Entity Instance But not want it to be stored(non-persistent)

Sometimes I need instantiate CoreDateEntity to store some infomations for temporarily using.
But I needn't it be stored into DB.
currently I created a similar class which have same structures as the CoreDateEntity does.
It works well but I have to do many datas transfer between Two models.
Is there any better way to handle this?
Thanks for all the replies. but you guys just give me half answer of this. consider about this, I need place some entity without MOC into current database pool, how could I do this? I already checked the documents of CoreData, seems I didn't find API to transfer one entity from MOC to another MOC(manage object context).
According to Apple docs you can initialize a managed object without context if you specify nil as context.
- (id)initWithEntity:(NSEntityDescription *)entity insertIntoManagedObjectContext:(NSManagedObjectContext *)context
You can assign entities to different stores when you set up the data model. Have one store be the persistent store and the other an in-memory store. You can't form relationships across stores but it sounds like you don't need that.
To assign a configuration, hit the configuration tab (the one with the wrench icon) in the entity detail (where you give it its name, class and parent). When you create the persistent store, add the configuration name to the options dictionary.
Update:
I think you maybe overcomplicating things. It sounds like you have some managed objects that will be temporary and some that will persisted but sometimes you may want to save the temporary objects. I don't think you should bother trying to separate out the "temporary" objects. Doing so just adds complexity without any performance benefit. Instead, just use ordinary persisted objects and then delete the ones you don't want.
Always try the simplest solution first.
Use two different managed object context's and only save the objects from one context. Be careful not to set relationships between objects of two different context's - this doesn't work.

Detecting changes to a specific attribute of NSManagedObject

How can I detect changes to a specific attribute of an NSManagedObject? In my Core Data data model, I have a Product entity that represents a product for sale. The Product entity has several attributes: price, sku, weight, numberInStock, etc. Whenever the price attribute of a Product changes, I need to perform a lengthy calculation. Consequently, I would like to know when the price attribute of any Product changes, [edit] even if that change comes from merging a context saved on another thread. What is a good way to go about doing this? I have thousands of Product objects in my store; obviously it's not feasible to send each one an addObserver message.
I have been using NSManagedObjectContextObjectsDidChangeNotification to detect changes, but it only notifies me that a managed object has changed, not which attribute of that object has changed. I could redo the calculation whenever there's any change to a Product, but that results in useless recalculations whenever an irrelevant attribute has changed. I'm considering making a Price entity (that only contains a price attribute) and using a to-one relationship between Product and Price. This way, I can detect changes to Price objects in order to kick off the calculation. This seems excessively kludgy to me. Is there a better way?
Update:
#railwayparade pointed out that I could use the changedValues method of NSManagedObject to determine which properties have changed for each updated object. I completely missed that method, and it would totally solve my problem if the changes weren't being made on a background thread and merged into the main thread's context. (See next paragraph.)
I completely missed a subtlety about the way that NSManagedObjectContextObjectsDidChangeNotification works. As far as I can tell, when a managed object context saved on another thread is merged into a context on the main thread (using a mergeChangesFromContextDidSaveNotification:), the resulting NSManagedObjectContextObjectsDidChangeNotification only contains change information about objects that are currently in the main thread's managed object context. If a changed object isn't in the main thread's context, it won't be part of the notification. It makes sense, but wasn't what I was anticipating. Therefore, my thought of using a to-one relationship instead of an attribute in order to get more detailed change information actually requires examination of the background thread's NSManagedObjectContextDidSaveNotification, not the main thread's NSManagedObjectContextObjectsDidChangeNotification. Of course, it would be much smarter to simply use the changedValues method of NSManagedObject as #railwayparade helpfully pointed out. However, I'm still left with the problem that the change notification from the merge on the main thread won't necessarily contain all of the changes made on the background thread.
One point with regard to this thread,
The NSManagedObjectContextObjectsDidChangeNotification generated by Core Data indicates that a managed object has changed, but doesn't indicate which attribute has changed.
It actually does. The "changedValues" method can be used to query which attributes changed.
Something like,
if([updatedObjects containsKindOfClass:[Config class]]){
//if the config.timeInterval changed
NSManagedObject *obj = [updatedObjects anyObject];
NSDictionary *dict=[obj changedValues];
NSLog(#"%#",dict);
if([dict objectForKey:#"timeInterval"]!=nil){
[self renderTimers];
}
}
This type of circumstance is where you need a custom NSManagedObject subclass. You need the subclass because you are adding a behavior, reacting to a price change, to the managed object.
In this case, you would override the accessor for the price attribute. Create a custom subclass using the popup menu in the data model editor. Then select the price attribute and choose 'Copy Obj-C 2.0 Implementation to the Clipboard`. It will give you a lot of stuff but the key bit will look like this:
- (void)setPrice:(NSNumber *)value
{
[self willChangeValueForKey:#"price"];
[self setPrimitivePrice:value];
[self didChangeValueForKey:#"price"];
}
Just add the code to deal with the price change and you are done. Anytime a specific product's price changes, the code will run.
You could take a look at KVO (Key Value Observing). Not sure if there are wrappers built into Core Data API, but I know it's part of Objective-C.
I thought I would document my design decisions here in case they're useful to others. My final solution was based on TechZen's answer.
First, I'll start with a short, and hopefully clearer, restatement of the problem:
In my application, I want to detect changes to a specific attribute (price) of a managed object (Product). Furthermore, I want to know about those changes whether they're made on the main or a background thread. Finally, I want to know about those changes even if the main thread currently does not have the changed Product object in its managed object context.
The NSManagedObjectContextObjectsDidChangeNotification generated by Core Data indicates that a managed object has changed, but doesn't indicate which attribute has changed. My kludgy solution was to create a Price managed object containing a single price attribute, and to replace the price attribute in Product with a to-one relationship to a Price managed object. Now, whenever a change is made to a Price managed object, the Core Data NSManagedObjectContextObjectsDidChangeNotification will contain that Price object in its NSUpdatedObjectsKey set. I simply need to get this information to the main thread. This all sounds good, but there's a hitch.
My Core Data store is being manipulated by two threads. This is done in the "usual" way—there is a managed object context for each thread and a single shared persistent store coordinator. After the background thread makes changes, it saves its context. The main thread detects the context save via the NSManagedObjectContextDidSaveNotification and merges the context changes using mergeChangesFromContextDidSaveNotification:. (Actually, since notifications are received in the same thread they're posted in, the NSManagedObjectContextDidSaveNotification is received on the background thread and passed to the main thread via performSelectorOnMainThread: for merging.) As a result of the merge, Core Data generates a NSManagedObjectContextObjectsDidChangeNotification indicating the changed objects. However, as far as I can tell, the NSManagedObjectContextObjectsDidChangeNotification only includes those objects which are currently represented in the receiving context. This makes sense from the perspective of updating the UI. If a managed object isn't being displayed, it probably won't be in the context, so there's no need to include it in the notification.
In my case, my main thread needs to know about changes made to managed objects whether or not they're currently in the main thread's context. If any price changes, the main thread needs to queue an operation to process that price change. Therefore, the main thread needs to know about all price changes even if those changes are made on a background thread to a product that's not currently being accessed on the main thread. Obviously, since NSManagedObjectContextObjectsDidChangeNotification only contains information about objects currently in the main thread's context, it doesn't meet my needs.
The second option I thought of was to use the NSManagedObjectContextDidSaveNotification generated by the background thread when it saves its context. This notification contains information about all changes to managed objects. I already detect this notification and pass it to the main thread for merging, so why not peek inside and see all of the managed objects that have changed? You'll recall that managed objects are not meant to be shared across threads. Consequently, if I start examining the contents of NSManagedObjectContextDidSaveNotification on the main thread, I get crashes. Hmm ... so how does mergeChangesFromContextDidSaveNotification: do it? Apparently, mergeChangesFromContextDidSaveNotification: is specifically designed to work around the "don't share managed objects across threads" restriction.
The third option I thought of was to register for NSManagedObjectContextDidSaveNotification on the background thread and while still on the background thread convert its contents into a special PriceChangeNotification containing object IDs instead of managed objects. On the main thread, I could convert the object IDs back into managed objects. This approach would still require the to-one Price relationship so that changes in prices are reflected as changes to Price managed objects.
I based my fourth option on TechZen's suggestion to override the price setter in the Product managed object. Rather than use a to-one relationship to force Core Data to generate the notifications I needed, I went back to using a price attribute. In my setPrice method, I post a custom PriceChangeNotification. This notification is received on the background thread and is used to construct a set of Product objects with price changes. After the background thread saves its context, it posts a custom PricesDidChangeNotification which includes the object IDs of all Product objects whose prices have changed. This notification can be safely transferred to the main thread and examined because it uses object IDs instead of managed objects themselves. On the main thread I can fetch the Product objects referenced by those object IDs and queue an operation to perform the lengthy "price change" calculation on a new background thread.
Are you using an NSArrayController or some other controller? Presumably you need some way for the user to interact with the model. It's this point of interaction that give a nice hook for this type of update call. Perhaps the appropriate strategy is to observe the relevant properties of the array controller's arrangedObjects.