Core Data from code
context は View から受け取る他ない?
参照
swift
let fetchRequest = NSFetchRequest<NSFetchRequestResult>()
fetchRequest.entity = Category.entity()
guard let categories = try? context.fetch(fetchRequest) as? [Category] else {
return
}
for category in categories {
print(category.name ?? "-")
}
削除
swift
for category in categories {
context.delete(category)
}
新規作成 ( + 親子階層 )
swift
for x in ["金融", "英語", "IT"] {
let category = Category(context: context)
category.name = "xxx \(x)"
let notebook = Notebook(context: context)
notebook.category = category // <-- 子から親を指定している
notebook.name = "\(x) メモ"
}
保存 ( 各操作の最後にやる )
swift
do {
try context.save()
} catch {
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}