CoreDataにデフォルトのSQLiteのデータを読みこませる方法。
以前(ジャーナルモード)では下記のやり方でオッケーだったのですが、
(ジャーナルモードでのやり方) http://rakuishi.com/iossdk/2831/
iOS7以降?はデフォルトがWALになったので、少し変更が必要となりました。
結論を書いてしまうと単純なのですが、
以前は
- Hoge.sqlite
のみをコピーすればよかったのが、
WALモードでは
- Hoge.sqlite
- Hoge.sqlite-wal
- Hoge.sqlite-shm
の3つともコピーする必要があります。
というわけで、先ほどご紹介した http://rakuishi.com/iossdk/2831/ に書かれているコードを変更すると以下のようになります。
(わかりやすくするため、冗長に書いています。)
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (__persistentStoreCoordinator != nil)
{
return __persistentStoreCoordinator;
}
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"Hoge.sqlite"];
NSString *writableDBPath_wal = [documentsDirectory stringByAppendingPathComponent:@"Hoge.sqlite-wal"]; //ここ追加
NSString *writableDBPath_shm = [documentsDirectory stringByAppendingPathComponent:@"Hoge.sqlite-shm"]; //ここ追加
NSString *storePath = [[NSBundle mainBundle] pathForResource:@"Hoge" ofType:@"sqlite"];
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Hoge.sqlite"];
NSLog(@"store URL %@", storeURL);
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:writableDBPath]) {
NSString *defaultStorePath = [[NSBundle mainBundle] pathForResource:@"Hoge" ofType:@"sqlite"];
NSString *defaultStorePath_wal = [[NSBundle mainBundle] pathForResource:@"Hoge" ofType:@"sqlite-wal"]; //ここ追加
NSString *defaultStorePath_shm = [[NSBundle mainBundle] pathForResource:@"Hoge" ofType:@"sqlite-shm"]; //ここ追加
if (defaultStorePath) {
[fileManager copyItemAtPath:defaultStorePath toPath:writableDBPath error:NULL];
[fileManager copyItemAtPath:defaultStorePath_wal toPath:writableDBPath_wal error:NULL]; //ここ追加
[fileManager copyItemAtPath:defaultStorePath_shm toPath:writableDBPath_shm error:NULL]; //ここ追加
NSLog(@"storePath= %@", storePath);
}
}
NSError *error = nil;
__persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
return __persistentStoreCoordinator;
}