Swift5 CoreData 保存の解説

# Swift5.0 CoreDataをDocumentsへ保存する話 ?

2019/05/03

> 必要な条件は ?

- 新規Productで名前はCDSaveでUse Core Dataにチェックをして作成します
- 作成後にAppDelegate.swiftとViewController.swiftを差し替えます
- CDSave.xcdatamodelファイルには何もしてません
- SQlite3というディレクトリーは私が勝手に作成したものです
- AppDelegate.swiftの91行目までは自動で作成されます
- GeneralのSigningでTeamに入力がないとCoreDataが利用できないようですよ ? 入れないとエラーが出てRunできません

> これでDocuments内に「ここまで省略/Documents/SQlite3/CDSave.sqlite」のように3種類のファイルが保存されます、それではソースを見てください

```AppDelegate.swift

//
//  AppDelegate.swift
//  CDSave
//
//  Created by 福田敏一 on 2019/05/03.
//  Copyright © 2019 株式会社パパスサン. All rights reserved.
//

import UIKit
import CoreData

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        return true
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
        // Saves changes in the application's managed object context before the application terminates.
        self.saveContext()
    }

    // MARK: - Core Data stack

    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: "CDSave")
        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
    }()

    // MARK: - Core Data Saving support

    func saveContext () {
        let context = persistentContainer.viewContext
        if context.hasChanges {
            do {
                try context.save()
            } catch {
                // エラー処理
            }
        }
    }
    
//2019/5/3・ここから・保存に必要なコードです
    
//2019/5/3・iOS 10以前のクラス
    lazy var managedObjectModel: NSManagedObjectModel = {
        // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
//2019/05/03・.mondとは ? momdファイルは実際にはすべてのバージョンモデルを含むコンテナ
        let modelURL = Bundle.main.url(forResource: "CDSave", withExtension: "momd")!
print("96通過・modelURL by AppDelegate -> \(modelURL)\n")
        return NSManagedObjectModel(contentsOf: modelURL)!
    }()
    lazy var applicationDocumentsDirectory: NSURL = {
        // The directory the application uses to store the Core Data store file. This code uses a directory named "com.test.ConfigurationTest" in the application's documents Application Support directory.
        let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
print("102AppDelegate・通過・urls by AppDelegate -> \(urls)\n")
print("103AppDelegate・通過・urls.count by AppDelegate -> \(urls.count)\n")
        return urls[urls.count-1] as NSURL
    }()
//2019/5/3・iOS 10以前のクラス
    lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
        // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added 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.
        // Create the coordinator and store
        let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
        let url = applicationDocumentsDirectory.appendingPathComponent("CDSave.sqlite")
print("112通過・url by AppDelegate -> \(url!)\n")//urlはディレクトリーなし
        // パスを作成
        let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! + "/SQlite3"
        do {
            // ディレクトリが存在するかどうかの判定
            if !FileManager.default.fileExists(atPath: path) {
                // ディレクトリが無い場合ディレクトリを作成する
                try FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: false , attributes: nil)
            }
        } catch {
            // エラー処理
        }
        // 保存先のパスを作成
        let savePath = path + "/CDSave.sqlite"
print("126・通過・savePath by AppDelegate -> \(savePath)\n")
        // 「パス」を「ファイルURL」に変換
        let urlURL = URL(fileURLWithPath: savePath)
print("129通過・urlURL by AppDelegate -> \(urlURL)\n")
        do {
            try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: urlURL, options: nil)
        } catch {
            // エラー処理
        }
        return coordinator
    }()
    lazy var managedObjectContext: NSManagedObjectContext = {
        // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
        let coordinator = self.persistentStoreCoordinator
        var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
        managedObjectContext.persistentStoreCoordinator = coordinator
print("142通過・managedObjectContext by AppDelegate -> \(managedObjectContext)\n")
        return managedObjectContext
    }()
    
}

//実行結果・以下はコンソールに表示されます
96通過・modelURL by AppDelegate -> file:///Users/papassan/Library/Developer/CoreSimulator/Devices/D615B742-2818-4124-B905-6014507443AD/data/Containers/Bundle/Application/1DF3C403-F9B4-4FEB-8144-4A6CB14F8E88/CDSave.app/CDSave.momd/

102AppDelegate・通過・urls by AppDelegate -> [file:///Users/papassan/Library/Developer/CoreSimulator/Devices/D615B742-2818-4124-B905-6014507443AD/data/Containers/Data/Application/D44D9B2B-7BAB-4828-8FE4-AA87540D4DD4/Documents/]

103AppDelegate・通過・urls.count by AppDelegate -> 1

112通過・url by AppDelegate -> file:///Users/papassan/Library/Developer/CoreSimulator/Devices/D615B742-2818-4124-B905-6014507443AD/data/Containers/Data/Application/D44D9B2B-7BAB-4828-8FE4-AA87540D4DD4/Documents/CDSave.sqlite

126・通過・savePath by AppDelegate -> /Users/papassan/Library/Developer/CoreSimulator/Devices/D615B742-2818-4124-B905-6014507443AD/data/Containers/Data/Application/D44D9B2B-7BAB-4828-8FE4-AA87540D4DD4/Documents/SQlite3/CDSave.sqlite

129通過・urlURL by AppDelegate -> file:///Users/papassan/Library/Developer/CoreSimulator/Devices/D615B742-2818-4124-B905-6014507443AD/data/Containers/Data/Application/D44D9B2B-7BAB-4828-8FE4-AA87540D4DD4/Documents/SQlite3/CDSave.sqlite

142通過・managedObjectContext by AppDelegate -> <NSManagedObjectContext: 0x600003eb84b0>

```


```ViewController.swift

//
//  ViewController.swift
//  CDSave
//
//  Created by 福田敏一 on 2019/05/03.
//  Copyright © 2019 株式会社パパスサン. All rights reserved.
//

import UIKit
import CoreData

class ViewController: UIViewController {
    
    //管理オブジェクトコンテキスト
    var contextSaveFile: NSManagedObjectContext!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        let applicationDelegate = UIApplication.shared.delegate as! AppDelegate
        contextSaveFile = applicationDelegate.managedObjectContext
    }
    
}

```

ここまで