LoginSignup
16
16

More than 5 years have passed since last update.

CoreDataに簡単に初期データを追加する

Last updated at Posted at 2014-04-20

NTYPopulatorというライブラリで簡単に初期データを追加できる。CocoaPodsからインストールできる。

Podfile
pod "NTYPopulator"
$ pod install

使い方はAppDelegate.mに一行加えるだけ。

AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [[NTYPopulator new] run];
    return YES;
}

リソースバンドル内にあるseeds/*.csvを探しだして、ファイル名と同名のEntityにデータを追加する。例えば、seeds/user.csvのデータはUserというEntityに追加される。

デフォルトではモデルファイルとしてModel.momdが参照され、SQLiteファイルとして$(CFBundleName).sqliteが参照される。これを変更することも可能。

AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"MyModel" withExtension:@"momd"];
    NSURL *documentDirectoryURL = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
    NSURL *sqliteURL = [documentDirectoryURL URLByAppendingPathComponent:@"MySQLite.sqlite"];

    NTYPopulator *populator = [[NTYPopulator alloc] initWithModelURL:modelURL sqliteURL:sqliteURL];
    [populator run];

    return YES;
}

以上、ステマでした。


追記

NTYPopulatorで想定していたユースケースは開発時に初期データをさくっと入れたいというものなので、リリース時には作成済みのSQLiteファイルを使った方がいいと思う。

16
16
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
16
16