InformIT: Introduction to Migration in Apple’s Core Data > Adjusting Your Code.

Adjusting Your Code

By default, data migration is not turned on for any application. Fortunately it is very easy to turn on automatic code migration, but the manner in which you turn it on is dependent on the type of application you are designing. When it comes to Core Data, there are two application models that differ drastically in their handling of the Core Data Stack: the document model and the non-document model.

Document Model

In a document model, each document has its own Core Data stack that is constructed when the NSPersistentDocument is initialized. In this case, to enable Core Data automatic migration you simply need to override one method call in your subclass of the NSPersistentDocument:

When Core Data attempts to load a persistent store, this method is called. To turn on automatic migration, all that is needed is to add the option in the store options as follows:

Once you have set the NSMigratePersistentStoresAutomaticallyOption flag, Core Data will attempt to automatically migrate any persistent store that does not match the store that is flagged as current.

Non-Document Model

Things are a bit different in a non–document-based application. Generally, the loading and handling of the Core Data stack is performed in the application delegate instead of in a document object. Therefore configuring Core Data to do automatic migration is also a bit different.

Normally, a non–document-based application will have a method to load up the persistent store that looks something like the following:

The only change that is required to turn on automatic store migration is to add the option, similar to the document model above, to the -(id)addPersistentStoreWithType: configuration: URL: options: error: method. You can see the change in the updated method below:

With that one change, Core Data will detect and migrate your persistent stores automatically.

Leave a Reply

电子邮件地址不会被公开。 必填项已用*标注