この場合、マイグレーション処理をAppDelegateのdidFinishLaunchingWithOptionsの中で行うと、アプリ起動時間制限(約20秒)に収まらない場合は、アプリがクラッシュする。
これを回避しながらCore Data自動マイグレーションを実行する方法。
「マイグレーション要否判定つきのCore Data 自動マイグレーション」は下記を参照。
http://iphone-app-developer.seesaa.net/article/272596714.html
[ AppDelegate.m ]
didFinishLaunchingWithOptions
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{[self update];
dispatch_async(dispatch_get_main_queue(), ^{
});
});
return YES;
}
新たに追加するupdateメソッド
-(void)update{
if ([self shouldPerformCoreDataMigration])
{
if ([self performMigration] == NO)
{
__persistentStoreCoordinator = nil;
}
[self persistentStoreCoordinator];
}
// Migration end
MasterViewController *masterViewController = [[[MasterViewController alloc] initWithNibName:@"MasterViewController" bundle:nil] autorelease];
self.navigationController = [[[UINavigationController alloc] initWithRootViewController:masterViewController] autorelease];
masterViewController.managedObjectContext = self.managedObjectContext;
self.window.rootViewController = self.navigationController;
[self.window makeKeyAndVisible];
}
didFinishLaunchingWithOptionsの中で、GCDを使用してupdateメソッドを呼び出し、マイグレーション要否判定〜マイグレーション処理〜Viewの表示を行う。
Xcode4.3からMaster-Detail ApplicationをCore Data付きで作成したテンプレートでは、didFinishLaunchingWithOptionsの中でmasterViewControllerをUINavigationControllerのRootViewControllerにして表示する。
このとき、managedObjectContextインスタンスを取得するが、updateメソッドにマイグレーション処理を移しただけではマイグレーション処理が終了する前にmanagedObjectContextインスタンスを取得してしまうため、Core Data不整合でアプリがクラッシュする。
このため、didFinishLaunchingWithOptionsメソッドではなくupdateメソッドにおいてmasterViewControllerの表示と、managedObjectContextインスタンスを取得を記述する。
ただ、これだとマイグレーション処理はViewが表示される前に実行されるため、画面上には何も出てこない。
ユーザには真っ暗な画面のまま固まっている状態である印象を与えてしまう。
ユーザビリティを考慮するならば、ModalViewなどでマイグレーション処理中であることを画面に表示する必要がある。
この場合は、AppDelegateではなく、初期表示するViewの中でマイグレーション制御(マイグレーション要否判定〜マイグレーション処理中画面の表示〜マイグレーション処理)を行うのが望ましい。
参考記事:
http://cocoadays.blogspot.jp/2011/02/coredata-coredatamanager.html
http://yoo-s.com/topic/detail/381