Skip to main content

Core Data 基本

作り方

  1. Model の追加
    • 新規ファイル > Core Data > Data Model
      • -> *.xcdatamodeld ファイルが作られる (末尾がd?)
    • Configuration
      • Default
        • CloudKit 使う場合は Used with CloudKit にチェックを入れる
  2. Entity の追加
    • Model 開いた状態で 画面左下 > Add Entity

設定項目メモ

  • Entities

    • 先頭大文字である必要あり
  • Attributes

  • Relationships

    • Destination
      • 関連先
    • Inverse
      • 紐づいている先を記載しているだけ?何に使う?
      • No Inverse?
    • Type
      • To-One
      • To-Many
    • Delete Rule
      • Deny : 接続先があったら消さない
      • Nullify : 関連のみ削除。紐づいたレコードを削除
      • Cascade : 紐づいたレコードも削除
      • No Action : 関連もレコードも消さない
  • Allows External Storage

  • Codegen : Class Definition

txt
File --- Persistent Store --- Model
|
Context ------------ Application

コード例

初期化

swift
let container = NSPersistentContainer(name: "Model") // これは Model.xcdatamodeld の名前
container.viewContext.automaticallyMergesChangesFromParent = true
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})

参照

swift
@FetchRequest(sortDescriptors: [], predicate: nil, animation: .default) private var listOfBooks: FetchedResults<Books>
...
ForEach(listOfBooks) { book in
RowBook(book: book)
}
...
Text(book.title)
Text(book.author.name) // book -> author の関連

保存

insert

swift
@Environment(\.managedObjectContext) var dbContext
@Environment(\.dismiss) var dismiss

await dbContext.perform { // ★★
let newBook = Books(context: dbContext) // これで新規レコード
newBook.title = ...
...
do {
try dbContext.save()
dismiss()
} catch {
print("Error saving record")
}
}

update

entity の値を更新したあとで dbContext.save()

delete

dbContext.delete(record) したあとで dbContext.save()

Entitiy に accessorつけたい場合は extension する

swift
extension Books {
var showTitle: String {
return title ?? "Undefined"
}
...
}