I have a Core Data application which I plan to update with a new schema. The lightweight migration seems to work, but it takes time proportional to the amount of data in the dat
You can't put migration in a NSOperation
because it will need to run on the main thread. What you need to do is to get out of the -applicationDidFinishLaunching:
method without touching the Core Data stack. If you can finish that method (and that run loop cycle) quickly then your app will not be terminated and you can take as long as the user will put up with to finish your migration.
See my answer here: How to switch from Core Data automatic lightweight migration to manual?
To clarify my position on this. It is inherently possibly to do just about anything. However, doing a migration on a background thread is a bad idea. It is extremely difficult to guarantee that the stack will never get touched during the migration as well as a whole host of other threading specific complications.
It is possible to do it but it involves a high degree of risk that is completely unnecessary. The main thread can and should be used to do a migration of the main Core Data stack. It is easy to put up a modal dialog to let the user know a migration is occurring and then perform the migration on the main thread.
If you are in a situation where your migrations are taking a signficant amount of time then it is also highly recommended that you switch from automatic migration to manual migration with a mapping model so that you can:
A lot has changed since this was originally answered.
The answer now for migrations is to fire them on a background queue (via dispatch_async
of the NSPersistentStoreCoordinator
's addStore...
call).
This also means that you need to make sure your UI can handle the persistence layer being empty/not available for an unknown period of time. How to do that depends on your application.
For example, you can have a temporary UI that shows dancing cats while the persistence layer does the migration. The user experience is up to you.
However, you do NOT want to let the user create data while the migration is happening. That will make it difficult to merge later (if at all).