LoginSignup
29
28

More than 5 years have passed since last update.

CoreDataでデフォルトデータを読みこませる WALのとき(iOS7)

Last updated at Posted at 2013-11-06

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;
}
29
28
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
29
28