Swift5 CoreData 保存の解説 2

# Swift5.0 CoreData ENTITIESを作成して保存する話 ?

最初の投稿でViewController.swiftの更新をしてませんでした、現在は更新しました、済みませんでした

2019/05/04

> 必要な条件は ?

- Swift5 CoreData 保存の解説の続き ?
- CDSave.xcdatamodelファイルのENTITIESにPeopleを作成
- 同じくAttributesにnameを作成してTypeはStringにします
- また、ENTITIESを選択してShow the Inspectorsを選択してClassのModuleとかには何もしてません
- ViewController.swiftに変更を加えました

> ViewController.swiftを参考にしてラベルとテキストを追加してください、Runをしてテキストフィールドに数文字を入力してReturnキーでラベルに入力結果が表示してテキストフィールドは空白になり変更結果がCDSave.sqliteファイルに反映されます、次にアプリを停止して再度Runするとラベルフィールドに前回の保存結果が表示すればOKの作動です

- 注意点は ? 過去のCDSave.sqliteが存在してると何だかんだとコンソールに警告が出ますので過去のそれらの3つのファイルは削除するかシムレーターの過去のアプリを削除してください
- 追加したデータの削除のコードはありません

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

import UIKit
import CoreData

class ViewController: UIViewController, UITextFieldDelegate {
    
    @IBOutlet weak var テキスト: UITextField!
    @IBOutlet weak var ラベル: UILabel!
    
    var people: [People] = []
    //管理オブジェクトコンテキスト
    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
        //管理オブジェクトコンテキストからpeopleエンティティを取得する。
        let fetchRequest: NSFetchRequest<People> = People.fetchRequest()
        
        do {
            people = try contextSaveFile.fetch(fetchRequest)
            //すべてのpeopleエンティティの名前をラベルに表示する。
print("34通過・people.count -> \(people.count)")
            for i in 0..<people.count {
                ラベル.text = ラベル.text! + "," + String(people[i].name!)
            }
        } catch {
            print(error)
        }
        //デリゲート先にselfを設定する。
        テキスト.delegate = self
    }
    //Returnキー押下時の呼び出しメソッド
    func textFieldShouldReturn(_ textField:UITextField) -> Bool {
        //ラベルの値にテキストフィールドの値を連結追記する。
        do {
        ラベル.text = ラベル.text! + "," + テキスト.text!
            //新しいPeopleエンティティを管理オブジェクトコンテキストに格納する。
            let 人々 = NSEntityDescription.insertNewObject(forEntityName: "People", into: contextSaveFile)
            //Peopleエンティティの名前nameにテキストフィールドの値を設定する。
            人々.setValue(テキスト.text, forKey:"name")
            
            //管理オブジェクトコンテキストの中身を永続化する。
            try contextSaveFile.save()
        //キーボードをしまう
        self.view.endEditing(true)
        } catch {
            print(error)
        }
        テキスト.text = ""
        return true
    }
    
}

//実行結果・以下はコンソールに表示されます

129・通過・savePath by AppDelegate -> /Users/papassan/Library/Developer/CoreSimulator/Devices/D615B742-2818-4124-B905-6014507443AD/data/Containers/Data/Application/3CE4D74A-867E-4D86-823D-F693A3F8BA16/Documents/SQlite3/CDSave.sqlite

34通過・people.count by ViewController -> 0


```

```AppDelegate.swift

//
//  AppDelegate.swift
//  CDSave
//
//  Created by 福田敏一 on 2019/05/04.
//  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 {
                // 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.
                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    }
    
//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("99通過・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("105AppDelegate・通過・urls by AppDelegate -> \(urls)\n")
//print("106AppDelegate・通過・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("115通過・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("129・通過・savePath by AppDelegate -> \(savePath)\n")
        // 「パス」を「ファイルURL」に変換
        let urlURL = URL(fileURLWithPath: savePath)
//print("132通過・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("145通過・managedObjectContext by AppDelegate -> \(managedObjectContext)\n")
        return managedObjectContext
    }()
    
}

```


ここまで