LoginSignup
6
11

More than 5 years have passed since last update.

CoreDataに予めデータを登録しておく方法 [Swift4]

Last updated at Posted at 2017-11-08

アプローチ

事前にsqliteファイルを作って、それを読み込ませる!

前提

・CoreDataをプロジェクトに追加済み
 ちなみに、既存プロジェクトにCoreDataを追加する方法はこちら
・CoreDataの基礎知識を持っている

手順

1. 初期データ登録処理のコードを書く

CoreDataを介してsqliteファイルを作れば、カラム規定などに悩まず済む

2. 作成したsqliteファイルを抽出する

抽出方法はこちら
必ず、sqlite for browserなどで中身を確認すること

3. プロジェクトに追加

普通にAdd a new fileするだけ

4. persistentContainerの中に処理を追加

"XXX"に、sqliteファイルの名前を入れる
コピペでいけるはず


    lazy var persistentContainer: NSPersistentContainer = {
        /*
         The persistent container for the application. This implementation
         creates and returns a container, having loaded the store for the
         application to it. This property is optional since there are legitimate
         error conditions that could cause the creation of the store to fail.
         */

        let container = NSPersistentContainer(name: "XXX")

        var persistentStoreDescriptions: NSPersistentStoreDescription

        // Documentsディレクトリのパスを取得
        let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        let documentsDirectory = paths[0]

        // sqliteファイルが置かれるURL
        let storeUrl = documentsDirectory.appendingPathComponent("XXX.sqlite")

        // そのURLにファイルが存在しない(=基本は初期化時)時、
        // 事前に作成したsqliteファイルをそこにコピーする
        if !FileManager.default.fileExists(atPath: (storeUrl.path)) {
            let seededDataUrl = Bundle.main.url(forResource: "XXX", withExtension: "sqlite")
            try! FileManager.default.copyItem(at: seededDataUrl!, to: storeUrl)
        }

        // 各種設定
        let description = NSPersistentStoreDescription()
        description.shouldInferMappingModelAutomatically = true
        description.shouldMigrateStoreAutomatically = true
        description.url = storeUrl

        container.persistentStoreDescriptions = [description]

        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

                /*
                 Typical reasons for an error here include:
                 * The parent directory does not exist, cannot be created, or disallows writing.
                 * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                 * The device is out of space.
                 * The store could not be migrated to the current model version.
                 Check the error message to determine what the actual problem was.
                 */
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        return container
    }()

参考

Swift 3 preload from SQL files in appDelegate (stackoverflow)
iOS開発メモ9 (XcodeでCore Dataを使う)
公式ドキュメント Core Data Programming Guide
NSPersistentStoreDescription のデフォルト値とカスタマイズ

おわりに

より良いアプローチがあったら是非コメントお願いします。

6
11
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
6
11