Swift5 CoreData 保存の解説 3

# Swift5.0 CoreData 2種類の保存の話 ?

2019/05/05

> 目的 : 1つのアプリ内に内部保存と外部保存を作成して不幸に外部ファイルが何者かに削除された場合に復元を検討しています、私の場合共通のデバイス環境で不注意にも削除してしまうことがあるから ?

> 定義

- 内部保存とは ? Swift5 CoreData 保存の解説 2でない保存方法 ? 
- 外部保存とは ? Swift5 CoreData 保存の解説 2の保存方法です

> 説明が分かりづらい ? つまり内部保存とは「2019-05-05 16:24:31.783449+0900 CDSave[1574:71637] [MC] System group container for systemgroup.com.apple.configurationprofiles path is /Users/papassan/Library/Developer/CoreSimulator/Devices/D615B742-2818-4124-B905-6014507443AD/data/Containers/Shared/SystemGroup/systemgroup.com.apple.configurationprofiles」に保存される事 ? しかし、そこには「CDSave.sqlite」のようなファイルが見つからない ?

> 改めて外部保存とは「/Users/papassan/Library/Developer/CoreSimulator/Devices/D615B742-2818-4124-B905-6014507443AD/data/Containers/Data/Application/C04933C5-3AEE-4142-91C0-4EAB5885CE47/Documents/SQlite3/CDSave.sqlite」の用に保存される事です

> 外部ファイルの利点は外部ファイルをSQlite3フォルダごとにバックアップしておけば削除しても復元できます
将来は内部保存から外部保存を作成する予定です

> 必要な条件は ?

- Swift5 CoreData 保存の解説2の続き ?
- CDSave.xcdatamodelファイルはそのままで変更なしです
- ViewController.swiftに変更を加えました
- AppDelegate.swiftは変更してません
- 削除機能のコードは まだありません

```ViewController.swift

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

import UIKit
import CoreData

class ViewController: UIViewController, UITextFieldDelegate {
    
    @IBOutlet weak var テキスト共用: UITextField!
    
    @IBOutlet weak var ラベル内部保存用: UILabel!
    @IBOutlet weak var ラベル外部保存用: UILabel!
    
    var peopleの内部用配列: [People] = []
    var peopleの外部用配列: [People] = []
    //管理オブジェクトコンテキスト
    var context: NSManagedObjectContext!
    var contextSaveFile: NSManagedObjectContext!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
//内部用
        let fetchRequest内部用: NSFetchRequest<People> = People.fetchRequest()
        //内部用の管理オブジェクトコンテキストを取得する。
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        context = appDelegate.persistentContainer.viewContext
        do {
            peopleの内部用配列 = try context.fetch(fetchRequest内部用)
            //すべてのpeopleエンティティの名前をラベルに表示する。
print("37通過・peopleの内部用配列.count -> \(peopleの内部用配列.count)")
            for i in 0..<peopleの内部用配列.count {
                ラベル内部保存用.text = ラベル内部保存用.text! + "," + String(peopleの内部用配列[i].name!)
            }
        } catch {
            print(error)
        }
//ここまで・内部用
//外部用
        let fetchRequest外部用: NSFetchRequest<People> = People.fetchRequest()
        //外部用の管理オブジェクトコンテキストを取得する。
        let applicationDelegate = UIApplication.shared.delegate as! AppDelegate
        contextSaveFile = applicationDelegate.managedObjectContext
        do {
            peopleの外部用配列 = try contextSaveFile.fetch(fetchRequest外部用)
            //すべてのpeopleエンティティの名前をラベルに表示する。
print("53通過・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!
            ラベル外部保存用.text = ラベル外部保存用.text! + "," + テキスト共用.text!

            //内部用エンティティを管理オブジェクトコンテキストに格納する。
            let 内部保存の人々 = NSEntityDescription.insertNewObject(forEntityName: "People", into: context)
            内部保存の人々.setValue(テキスト共用.text, forKey:"name")
            
            let 外部保存の人々 = NSEntityDescription.insertNewObject(forEntityName: "People", into: contextSaveFile)
            外部保存の人々.setValue(テキスト共用.text, forKey:"name")
            
            //管理オブジェクトコンテキストの中身を永続化する。
            try context.save()//内部用
            try contextSaveFile.save()//外部用
        //キーボードをしまう
        self.view.endEditing(true)
        } catch {
            print(error)
        }
        テキスト共用.text = ""
        return true
    }
    
}

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

37通過・peopleの内部用配列.count -> 0
129・通過・savePath by AppDelegate -> /Users/papassan/Library/Developer/CoreSimulator/Devices/D615B742-2818-4124-B905-6014507443AD/data/Containers/Data/Application/F9E91DE3-B95B-45DB-B2A9-FAB5452EEFC8/Documents/SQlite3/CDSave.sqlite

53通過・peopleの外部用配列.count -> 0
2019-05-05 16:30:22.633986+0900 CDSave[1639:76088] [MC] System group container for systemgroup.com.apple.configurationprofiles path is /Users/papassan/Library/Developer/CoreSimulator/Devices/D615B742-2818-4124-B905-6014507443AD/data/Containers/Shared/SystemGroup/systemgroup.com.apple.configurationprofiles
2019-05-05 16:30:22.635056+0900 CDSave[1639:76088] [MC] Reading from private effective user settings.


```

```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
    }()
    
}

```


ここまで