「App Extension」とは?
App extensions は、主要iOSアプリケーションの拡張機能です。例えば、「iMessage Extension」、「Today Extension」、「Siri Extension」などがあります。

##「Core Data」とは?
Core Data はAppleのフレームワークであり、ユーザー情報をローカルストレージに格納するのに便利です。また、CloudKitのサポートも組み込まれており、ユーザーたちのすべてのデバイスで変更内容を同期できます。
本日のトピック?
Core Data には、次のコードを使用することで、主要iOSアプリで簡単にアクセスできます:
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
ただし、App Extensionからもアクセスできるようにするには、いくつかの追加の手順を行う必要があります。
警告:この変更は、既存のアプリを更新する時にではなく、未公開のアプリを最初に開発する段階で行ってください。
複数のApp ExtensionにわたるCore data
1. App Group を有効にする
最初に「Signing & Capabilities」タブに進み、「+」アイコンを選択します。

主要iOSアプリとその他のすべてのターゲット向けに「App Group」を追加します。
すべてのターゲットに同じ「App Group」を割り当てます。

2. ヘルパーを追加
まずファイル「*. xcdatamodel」を探します。ファイル名が「Sakura.xcdatamodel」の場合、データベース名が「Sakura」ということです。
import Foundation
import CoreData
class NSCustomPersistentContainer: NSPersistentCloudKitContainer {
override open class func defaultDirectoryURL() -> URL {
var storeURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.[App Group Name 名前]")
storeURL = storeURL?.appendingPathComponent("Sakura.sqlite")
return storeURL!
}
}
3. データベースにアクセスする
これで次の方法でデータベースにアクセスできるようになりました:
lazy var persistentContainer: NSPersistentContainer = {
let container = NSCustomPersistentContainer(name: "Sakura")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
print(error.localizedDescription)
}
})
return container
}()
let context = persistentContainer.viewContext