What is the difference between mutable and immutable managed object model in Core Data? - ios

After reading RestKit docs about RKManagedObjectStore I was confused about createPersistentStoreCoordinator method because there is a next warning in the description of this method:
**Warning:** Creating the persistent store coordinator will
render the managed object model immutable. Attempts to
use functionality that requires a mutable managed object model
after the persistent store coordinator has been created
will raise an application error.
I didn't understant what does it mean immutable managed object model? I can't found any information about this topic neither in official Core Data docs nor accross the Internet. Can someone give me an explanation of the difference between mutable and immutable managed object models? Why does creating of persistent store coordinator renders immutable managed object model? And what functionality requires a mutable managed object model?
Thanks in advance.

You can change a NSManagedObjectModel (add entities and attributes for example) in code, it is said to be mutable. But once you attach your object model to an persistent store coordinator you are not allowed to change it anymore - it has become immutable.
This also is described in the documentation for NSManagedObjectModel:
Editing Models Programmatically Managed object models are editable
until they are used by an object graph manager (a managed object
context or a persistent store coordinator). This allows you to create
or modify them dynamically. However, once a model is being used, it
must not be changed. This is enforced at runtime—when the object
manager first fetches data using a model, the whole of that model
becomes uneditable. Any attempt to mutate a model or any of its
sub-objects after that point causes an exception to be thrown. If you
need to modify a model that is in use, create a copy, modify the copy,
and then discard the objects with the old model.

Related

NSManagedObject entity class method

I recently realized that NSManagedObject subclasses inherit a class method entity which can be used to obtain a NSEntityDescription for the class. However, I was used to having to specify a context when creating a NSEntityDescription, as with entityForName:inManagedObjectContext:. Is it ok to use the simpler entity method and what context will it be associated with ?
This method is not really documented by Apple.
An NSEntityDescription is not part of a managed object context-- it's part of the managed object model.
When you load a data model, all of the entity descriptions it contains are loaded. The class method +entity works because the entity description was created along with the model object. If you try to call this method before loading the model, it returns nil in Objective-C. (In Swift for some reason it returns a non-optional value, so it's not nil, but if you use it your app will crash. Don't ask me why it's like this.)
You can also use +entityForName:inManagedObjectContext:, as you mentioned. But look at the documentation for that method:
Returns the entity with the specified name from the managed object model associated with the specified managed object context’s persistent store coordinator.
So even though the method takes a managed object context argument, it's still using the managed object model. It's using the context to find the model. The object that you get isn't associated with the context, it's associated with the underlying data model.
These two methods are equally safe. Use whichever works best in your code.

Realm Swift: passing unpersisted objects between threads

I have a model some instances of which I need to persist. Only some, not all, since persisting all instances would be wasteful. The model has primaryKey of type Int
I need to be able to pass all objects from background to main thread since Realm objects can only be used by the thread on which they were created. Current version of Realm Swift (0.94) does not seem to support handing the object over to another thread directly.
For persisted objects (the ones saved to storage with write) this is not a problem, I can fetch the object on another thread by primaryKey.
Unpersisted objects, however, are problematic. When I create a new object with the same primaryKey in background (I suppose it should be treated as the same object since it has the same primaryKey) and try to fetch it on the main thread (without persisting changes with write since I don't want in in the storage), I seem to get the old object.
I see the following solutions to this problem:
1) persist all objects (which is undesirable and otherwise unnecessary)
2) keep separate model for the objects I want to persist (leads to code duplication).
3) use init(value: AnyObject) initializer which creates unpersisted object from a Dictionary<String, AnyObject> (would probably require manual copying of object properties to dictionary, tedious and potentially error-prone)
Are there any better solutions?
Offtopic: I haven't tried Realm for Android, is situation any better with it?
You are free to pass unpersisted objects between threads as you wish -- only persisted objects cannot yet be handed over between different threads.
I think your problem is that you are creating two objects that you want to be the same object and there is no way the system can know which one you want.
The solution is as simple as it is generic: create a new object only after checking that its unique attribute does not exist already. This should work equally well with persistent and non persistent objects. Obviously, you need to have a central, thread safe in-memory repository where you can go and create new objects.
You write:
I seem to get the old object.
There should not be any old object if you have checked before.

"NSInternalInconsistencyException" Entities for a configuration must already be in the model

I am trying to add a new entity in NSManagedObjectModel in my NSIncrementalStore Subclass. I am doing this in loadMetadata method but it keeps throwing this exception on the last line. See Code Below
"NSInternalInconsistencyException" Entities for a configuration must already be in the model
Code
var model:AnyObject=(self.persistentStoreCoordinator?.managedObjectModel.copy())!
var newEntity=NSEntityDescription()
newEntity.name="newEntity"
newEntity.managedObjectClassName="newEntity"
var entities=model.entitiesForConfiguration(self.configurationName)
entities?.append(newEntity)
model.setEntities(entities!, forConfiguration: self.configurationName)
You cannot modify a model after it has been added to a persistent store coordinator. The only time you can manipulate the model is just after initialization and before applying it to the NSPersistentStoreCoordinator.
The documentation is unclear about this, but before calling setEntities:forConfiguration: the entities being set must already exist in the managed object model's entities array. This is because this method actually assigns existing entities in the model to a particular configuration.
The solution here is to make a mutable copy of the entities array, add your entities to it if they do not exist, and then set the managed object model's entities array to an immutable copy of the modified array.
After that point you can invoke setEntities:forConfiguration:.
It would be worth filing a radar bug report on this behavior.

Create Core Data entities dynamically during runtime

I need to be able to create new core data entities during runtime. I've written the code to create the objects programmatically, however, I can't add the entities during runtime as the model is immutable.
My problem is similar to this post, however there is no satisfactory answer: How to dyanmic create a new entity (table) via CoreData model?
The documentation regarding changing the core data model explains:
Managed object models are editable until they are used by an object
graph manager (a managed object context or a persistent store
coordinator). This allows you to create or modify them dynamically.
However, once a model is being used, it must not be changed. This is
enforced at runtime—when the object manager first fetches data using a
model, the whole of that model becomes uneditable. Any attempt to
mutate a model or any of its sub-objects after that point causes an
exception to be thrown. If you need to modify a model that is in use,
create a copy, modify the copy, and then discard the objects with the
old model.
However, I'm unclear on what exactly this is saying--that the whole core data model can't be changed once the persistent store coordinator has been used or the attributes/etc of the individual entities can't be changed.
To be clear, I do not want to change the attributes of my current entities, I simply want to add new entities. It just seems weird to me to have to use migration to add new entities.
Any thoughts?
Thanks!
The documentation is pretty clear.
Copy the model.
Apply your changes to the new copy.
Destroy your old MOC, Persistent Store Coordinator, and all objects created from those.
Apply a migration, if necessary.
Create a new Core Data Stack (MOC, PSC, etc) using your updated model.
The migration could be a sticking point, but it should be do-able.

Understanding of NSCoreData and MSManagedObject subclasses

I am learning a bit on NSCoreData and before introducing it some existing projects I have, I would like to validate my good understanding of the core principles.
From what I have understood, NSCoreData make it easier to manage local storage of object (+retrieval after that) by subclassing our Model class from NSManagedObject rather than from NSObject.
Right ?
I have a few questions then. Let's consider I am building a real estate application with as core model object the class Property that can represent an appartment, a house, and all related information. Currently it is managed in my app as a subclass of NSObject.
1) I retrieve the properties from the server through a search query, and have written a initWithJson : method to populate each instance.
Now if I subclass Property from NSManagedObject, I will create my instances by using
+(id)insertNewObjectForEntityForName:(NSString *)entityName
inManagedObjectContext:(NSManagedObjectContext *)context
and I will be still be able to add a populateWithJson: to my class to fill in the properties.
Then I will create a lot of Property instances in the current managedObjectContext, and if I do a save, they will be stored at the physical layer.
If I call again the same webservice, and retrieve the same JSON content, I will recreate the identical managed objects.
How to avoid redundancy with the [managedObjectContext save:&error] call and not to store physically several time the representation of a single real life property ?
2) Let's say I want to store physically only some properties, for instance only the one the user want to have as favorites.
[managedObjectContext save:&error] will save all created / modified / deleted managed objects from the context to the physical layer, and not only the one I want.
How to achieve that ?
Am I supposed to declare another context (managedObjectContext2), move the instance I want to store in that context, and do the save in that one ?
(I mean, I will have a context just to manipulate the object, create instances from the JSON and represents them in UI ... and a second one to actually do the storage)
Or am I supposed to stores all the objects, and add a isFavorite BOOL property , and then fetching using a predicate on that property ?
3) The app has a common navigation pattern : the UITableView lists Properties instance with the minimum information required, and going on a detail view call a webservice to request more information on a specific Property instance (images, full text description).
Is it a good practice for instance to call the webservice only if the property.fullDescription is nil, and then update the object and store it locally with all detailed information, and the next time only to fetch it locally with a predicate on the property.id ?
What about object that might be updated server-side after they have been created?
Thanks for your lights
1) Retrieve the server data into a temporary form (array of dictionaries?), then for each possible property in the array, check to see if you already have an object in Core Data that matches. If you do, either ignore it or update any changed attributes; if not, create a Property object.
2) Decide which things you want to persist in order to support your app's functions. There's no point in creating a managed object for something you don't want to save. Note, though, that Core Data supports sub-classes if you want both Property and FavoriteProperty.
3) Entirely up to your "business rules"…. How often do you need local data to be updated? The only technical consideration might be the guideline to not keep large files locally that can be re-created on demand.

Resources