UIManagedDocument migrate data model - core-data

I am working on an iPhone app that uses a subclass of UIManagedDocument and stores its documents on iCloud.
It was all working fine until I changed my core data model / scheme (adding a new model version - like I had several times in the past few weeks).
I added a new property and changed the data type of one of the existing properties.
Now when I run my app I don't seem to be able to load my documents with UIManagedDocument's -openWithCompletionHandler:.
I can create new documents and read/write those.
If I change the data model version back 1 then I am able to read the existing docs, but not the new ones.
From what I understand I am only do lightweight migrations to the data model and UIManagedDocument is supposed to handle that right?
Any advice would be greatly appreciated!

Given below is based on my understanding:
NOTE - I haven't tried it for iCloud but I have tested it for non-icloud and seems ok.
UIManagedDocument configures the managedObjectModel and a Persistent Store Coordinator by itself
When migration needs to be done, just set the UIManagedDocument's persistentStoreOptions
//Note - In this example, managedDocument is a UIManagedDocument property
self.managedDocument.persistentStoreOptions = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
Refer:
Apple Documentation on Core Data Versioning
Point of using NSPersistentStoreCoordinator?

In a subclass of UIManagedDocument you may want to try overriding managedObjectModel like so:
- (NSManagedObjectModel *)managedObjectModel
{
NSString *path = [[NSBundle mainBundle] pathForResource:#"<ModelNameHere>" ofType:#"momd"];
NSURL *momURL = [NSURL fileURLWithPath:path];
NSManagedObjectModel *managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:momURL];
return managedObjectModel;
}

Related

Deleting CoreData journaling mode not migrating to new store

Since MagicalRecord 3.0 has not been released yet, I upgraded to 2.3 and tried to "turn off" journaling mode. This is my code:
// Code to disable journaling mode
NSManagedObjectModel *managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];
NSString *applicationDocumentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *urlString = [applicationDocumentsDirectory stringByAppendingPathComponent: #"saori.sqlite"];
NSURL *url = [NSURL fileURLWithPath:urlString];
NSDictionary *options = #{NSSQLitePragmasOption:#{#"journal_mode":#"DELETE"}};
NSPersistentStoreCoordinator *psc = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:managedObjectModel];
[psc addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url options:options error:nil];
What's happening is it's not only NOT turning off journaling mode, but it creates an entirely new (read empty) CoreData store with journaling.
Is there anything I can do outside of MR 3.0 so the contents of the journaled store are migrated to a new CoreData store without journaling?
MagicalRecord 3.0 will not change whether this works or not. This is a CoreData feature. MR 3.0 will provide you a way to specify options for adding a particular store, so it's less code. But the fact that Journalling or WAL mode are an issue, this is fundamental to how CoreData itself works. And in that case, moving to MR3 probably won't help you.

iOS Core Data App Delegate?

I am working on a app that is going to require the use of Core Data and I can't help but notice that Core Data has to be put in manually if you use anything but the Master-Detail, Utility or Blank templates in Xcode.
I also noticed that in order for Core Data to work properly, you HAVE to have your app wrapped in a Navigation Controller and Core Data's code in the AppDelegate files.
Anyone know of a way around this or is this the way it is supposed to be?
My App Delegate looks something like this and those three lines seem to be the most important setup for the ManagedObjectContext!
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
UINavigationController *navController = (UINavigationController *)self.window.rootViewController;
FBBetsViewController *controller = (FBBetsViewController *)navController.topViewController;
controller.managedObjectContext = self.managedObjectContext;
Those templates include some core data setup, but it is far from mandatory. You can use core data from within any project. If you want, you can just take the code from the empty application, and use it in your project.
If you look in the generated code, you will see three "getters" for the three main components used to build the core data stack.
managedObjectModel creates the model, by using the model file from your bundle. Create that easily in Xcode by New-File and selecting the Core Data Data Model.
persistentStoreCoordinator uses the model, and a SQL store.
Finally, managedObjectContext is created by using the persistentStoreCoordinator. Note, you really can build that stack in one method if you want. There is no requirement to have those individual accessors...
You could do something like this...
- (NSManagedObjectContext*)setupCoreDataStack
{
// Load the model description
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:#"APPNAME" withExtension:#"momd"];
NSManagedObjectModel *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
// Prepare the persistent store coordinator - needs the model
NSURL *documentsDirectory = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
NSURL *storeURL = [applicationDocumentsDirectory URLByAppendingPathComponent:#"APPNAME.sqlite"];
NSError *error = nil;
NSPersistentStoreCoordinator *psc = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
if (![psc addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error])
{
// Handle the error !!!!!
// exit the function
return nil;
}
// Create the managed object context. This is what you will really
// use in the rest of your program.
NSManagedObjectContext *moc = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
[moc setPersistentStoreCoordinator:psc];
return moc;
}
And now you have almost the same stack as the others. The only real difference is that the MOC here is using the main queue concurrency type, which is a much better alternative.
If you want to have a much better performance model, insert a parent moc.
Actually, if you are not married to a current cored data strategy, I'd suggest UIManagedDocument.
Core Data does not impose that you use a navigation controller nor that you set it up in the AppDelegate. It's customary to put the setup in the AppDelegate upon startup but really, you can move it wherever you want as long as you make sure it's only initialized once.

Migration issues with UIManagedDocument

I started using CoreData in my application following Stanford CS193P lessons regarding the use of iOS 5's new class UIManagedDocument. The approach itself is quite straightforward but I can't understand how to deal with model modifications i keep making. This is how I instantiate my UIManagedDocument object (inside the appDelegate, so that every other class can use it):
if (!self.database) {
NSURL *url=[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
url = [url URLByAppendingPathComponent:#"AppName"];
UIManagedDocument *doc = [[UIManagedDocument alloc] initWithFileURL:url];
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
doc.persistentStoreOptions = options;
self.database=doc;
[doc release];
}
The issue I have is that every time I change even a little bit of my .xcdatamodel, I am unable to get all the content previously stored in the document as well as to create any new instance. As a matter of fact doing this generates the following exception:
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'This NSPersistentStoreCoordinator has no persistent stores. It cannot perform a save operation.'
I thought setting the "options" property of the managed document would have solved the problem, but apparently this isn't enough.
Anyone can help? Couldn't' find other questions that actually fit my precise needs.
Before you modify your Core Data model, you should "Add Model Version".
1.
Select the original model file. (e.g. YourProject.xcdatamodel)
2.
"Editor" -> "Add Model Version...". Then add a new model version (e.g. 2.0)
3.
You will get a new model file. (e.g. YourProject 2.0.xcdatamodel). Modify it.
4.
Change the current model version. Select the top .xcdtatmodel file -> "View" -> "Utilities" -> "Show File Inspector". Find the tag "Versioned Core Data Model" and choose the right version you want to modify.
It also disturbed me for a long long time. Hope this way can help you ^^
There is a really simple solution to your problem. Simply erase the app from the simulator or device (touch the app icon for a few seconds, and touch the cross that appears when the app icons start wiggling). That way, Xcode updates your app's UIManagedDocument.
Make sure that you did not mistype NSDocumentDirectory as NSDocumentationDirectory.
NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
NSDocumentDirectory is right!

A Second In-Memory-Store As A Cache

Dear community.
I try to discover opportunity to using 2 persistent stores for improve performance of my application.
What i do here:
CREATE 2 PERSISTENT STORES
persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:mom];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:[NSNumber numberWithBool:YES]
forKey:NSMigratePersistentStoresAutomaticallyOption];
if (![persistentStoreCoordinator addPersistentStoreWithType:NSInMemoryStoreType
configuration:nil
URL:[NSURL URLWithString:#"memory://store"]
options:dict
error:&error])
{
[[NSApplication sharedApplication] presentError:error];
[persistentStoreCoordinator release], persistentStoreCoordinator = nil;
return nil;
}
if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil
URL:url
options:dict
error:&error])
{
[[NSApplication sharedApplication] presentError:error];
[persistentStoreCoordinator release], persistentStoreCoordinator = nil;
return nil;
}
ASSIGN new created objects to in-Memory store
NSManagedObject *objectCarrier = [NSEntityDescription
insertNewObjectForEntityForName:#"Carrier"
inManagedObjectContext:managedObjectContext];
[objectCarrier setValue:startForCarrier
forKey:#"name"];
NSURL *url = [NSURL URLWithString:#"memory://store"];
[managedObjectContext assignObject:objectCarrier
toPersistentStore:[[appDelegate persistentStoreCoordinator] persistentStoreForURL:url]];
SAVE FINAL OBJECT
A difference between in-memory and particular persistent store using is
i have wrong using objects from predicates for same code.
If i just change persistent store type, i pickup object:
NSManagedObject *destination = [[codeAfterComparing lastObject] valueForKey:codeRelationshipName];
But set values for this object is doesn't work.
If i try to assignObject for received object, i have error (it's doesnt matter, how this object was save as inMemory or asSqlLite store object, error is start every time).
2011-02-16 14:32:45.037 snow
server[44411:1803] * Terminating app
due to uncaught exception
'NSInvalidArgumentException', reason:
'Can't reassign an object to a
different store once it has been
saved.'
Attempt to save a final object's graph with two different stores gives me error "CoreData does not support persistent cross-store relationships", and it's doesn't matter, where cureent object assing.
Migration was as :
for (NSPersistentStore *persistentStore in [persistentStoreCoordinator persistentStores]) {
if (persistentStore.type == NSInMemoryStoreType) {
// migrate the in-memory store to a SQLite store
NSError *error;
[persistentStoreCoordinator migratePersistentStore:persistentStore toURL:[NSURL fileURLWithPath:[[self applicationSupportDirectory] stringByAppendingPathComponent:#"storedata.sql"]] options:nil withType:NSSQLiteStoreType error:&error];
if (! newPersistentStore) {
Product error: "Can't add the same store twice"
So, the result is a very strange for me:
1. Looks like managed object context have no difference for objects between 2 stores. If i ask save, it take whole object and save so same sqlite store
2. maybe a way to using different persistent store coordinator's but i don't know exactly, how is easy transfer objects between 2 stores. Of course, i can do a copy (include relationships e.t.c.) but this is a hard code for this simple issue, i guess.
Maybe somebody can suggest about my code wrong or good working examples of code to review and understand a good way to do in memory cache with core data? Google search gives not too much examples.
If you look at the Core Recipe example code on Apple's website, they use multiple stores to save objects in memory and on disk.
Thought I'd take a stab here.
I've had this problem in the past. I ended up removing the functionality for two persistent stores in the same coordinator. If I understand Apple correctly, Object Entities cannot be shared between persistent stores. So to make things easier, I usually just do the following (though I suspect there is an efficiency issue with using an additional Coordinator)
1 NSPersistentStore per NSPersistentStoreCoordinator
break up the scratchpad work to the NSManagedObjectContexts
create a deep-copy method to your NSManagedObject subclasses
And then, when whatever class you have managing each persistent store utilize the copy function to import the managed objects.
I can't really think of an instance where you'd want to go through the extra trouble of individually assigning the managed objects to a specific store that wouldn't be taken car of in this way.
I have a program that utilizes two stores - one in memory for transient objects and another managing the document. It's working just fine.
In iOS 5 Apple introduce Nested Managed Object Contexts where you can work with two Managed Object contexts.
This may replace your approach with the in memory store because e.g. you can now use one of the (also) new concurrency types to run one context in the background (e.g. for background fetching) and another as your main context.
Take a look in the WWDC2011 Session 303.

How can I use Core Data Objects outside of a managed object context?

I would like to use Core Data Managed Objects outside of a managed object context. I've seen other threads on this site that say you should never do this, but here's my issue:
I have a 'Feed' object and a 'story' object. Feed is like an RSS feed, and story is like a single story from that feed. I have the ability to bookmark feeds, and I use Core Data to persist those, but I when I download stories from a feed, I don't want to insert those stories into the managed object context. The only way to create my objects, however, is by doing this:
[NSEntityDescription insertNewObjectForEntityForName:name inManagedObjectContext:managedObjectContext];
Which means that it will be persisted at the next save event.
I don't want these objects to be persisted until the user selects them.
I tried defining a "TransientStory" and a "PersistentStory" with a protocol called "Story" that both of them implement, but it's a nightmare. Any ideas?
You can create these objects and just not insert them in the context:
NSEntityDescription *entity = [NSEntityDescription entityForName:entityName
inManagedObjectContext:managedContext];
ManagedObjectClass *volatileObject = [[ManagedObjectClass alloc] initWithEntity:entity
insertIntoManagedObjectContext:nil];
And if you want to save it you just insert it to the context:
[managedContext insertObject:volatileObject];
(if you forget to add it, it will give you a dangling object error when you try to save it in the context)
Create a new NSManagedObjectContext with an in-memory store. Then you can put your transient objects into this context, and they won't be persisted.
NSManagedObjectModel *mom = [NSManagedObjectModel mergedModelFromBundles:[NSArray arrayWithObject:[NSBundle mainBundle]]]; // though you can create a model on the fly (i.e. in code)
NSPersistentStoreCoordinator *psc = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:mom];
NSError *err;
// add an in-memory store. At least one persistent store is required
if([psc addPersistentStoreWithType:NSInMemoryStoreType configuration:nil URL:nil options:nil error:&err] == nil) {
NSLog(#"%#",err);
}
NSManagedObjectContext *moc = [[NSManagedObjectContext alloc] init];
[moc setPersistentStoreCoordinator:psc];
If you did want to then persist them, just move them to the proper store afterwards, or merge the context.
Alternatively, if you're eventually going to put them into that context anyway (i.e. you just don't want them appearing in lists until they're saved), then just set setIncludesPendingChanges to NO in your NSFetchRequest.

Resources