-
Notifications
You must be signed in to change notification settings - Fork 5
CoreData 학습
KYHyeon edited this page Nov 18, 2020
·
2 revisions
오늘의 주제: Core Data
학습한 내용을 정리하거나 참고자료를 올려주세요😀
-
코어 데이터 튜토리얼
-
Codegen에서의 Menu는 3가지가 있다.
- Manual/None은 Class, Extension
- Class Definition은 Class, Extension 필요없음
- Category/Extension은 Class만 필요
// Core Data save
// Setting
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
// 저장1
let person = Person(context: context)
person.age = 1
person.name = "name"
person.person = "person"
try? context.save()
// 저장2
let entity = NSEntityDescription.entity(forEntityName: "Person", in: context)
if let entity = entity {
let model = NSManagedObject(entity: entity, insertInto: context)
model.setValue(123, forKey: "age")
model.setValue("n", forKey: "name")
model.setValue("p", forKey: "person")
}
try? context.save()
// 출력
func fetchContact() {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
do {
let contact = try context.fetch(Person.fetchRequest()) as! [Person]
contact.forEach {
print($0.name)
}
} catch {
print(error.localizedDescription)
}
}
// 삭제
let request2: NSFetchRequest<Person> = Person.fetchRequest()
deleteAll(request: request2)
func deleteAll<T: NSManagedObject>(request: NSFetchRequest<T>) {
let request: NSFetchRequest<NSFetchRequestResult> = T.fetchRequest()
let delete = NSBatchDeleteRequest(fetchRequest: request)
try? self.context.execute(delete)
}