4

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!

Stuart
  • 36,683
  • 19
  • 101
  • 139
adamteale
  • 940
  • 2
  • 12
  • 27

2 Answers2

7

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:

Community
  • 1
  • 1
user1046037
  • 16,755
  • 12
  • 92
  • 138
  • where should these line of codes be put? I'm going through a similar problem. I placed it after my `self.database = [[UIManagedDocument alloc] initWithFileURL:url];` But my migration doesn't seem to be successful. – acecapades May 30 '13 at 02:37
  • Pls check the Apple Documentation link provided in my answer, the documentation explains all the steps required . I have used the above code in AppDelegate's `- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions`. – user1046037 May 30 '13 at 16:18
  • @user1046037 Awesome! This worked for me and saved me a ton of time. – dherrin79 Apr 04 '14 at 17:46
  • This one is definitely the correct answer. The one above is hard to understand and could cause the app to use different models. – idmean Apr 25 '15 at 16:50
2

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;
}
Daniel
  • 8,794
  • 4
  • 48
  • 71