Core Data (FrameWork)
Persist or cache Data on a single device, or sync data to multiple devices with CloudKit
데이터를 유지하거나 캐시할 수 있으며, ClouldKit을 사용하면 여러 장치에서 데이터를 동기활 할 수 있다.
프로젝트 새로운 파일 -> Data Model 파일을 생성한다.
// 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: "Model") // 생성한 Data Model 명
container.loadPersistentStores(completionHandler: {(storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
/*
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.
*/
}
})
return container
}()
// MARK: - Core Data Saving Support
func saveContext() {
let context = persistentContainer.viewContext
if context.hasChanges {
do{
try context.save()
}catch{
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
let car = Car()
이렇게 바로 사용할 수 있음func saveData(){
guard let context = self.persistentContainer?.viewContext else {return}
let newCar = Car(context : context)
newCar.id = UUID()
newCar.name = "Benz"
try? context.save()
}
// 데이터 읽기 (Read)
func readData(){
guard let context = self.persistentContainer?.viewContext else {return}
let request = Car.fetchRequest()
guard let cars = try? context.fetch(request) else{
return
}
print(cars)
}
// 데이터 수정 (Update)
func updateData(){
guard let context = self.persistentContainer?.viewContext else {return}
let request = Car.fetchRequest()
guard let cars = try? context.fetch(request) else {return}
let filteredCars = cars.filter{$0.name == "Benz"}
for car in filteredCars {
car.name = "tesla"
}
try? context.save()
}
// 데이터 삭제 (Delete)
func deleteData(){
guard let context = self.persistentContainer?.viewContext else {return}
let request = Car.fetchRequest()
guard let cars = try? context.fetch(request) else {return}
let filteredCars = cars.filter{$0.name == "tesla"}
for car in filteredCars {
context.delete(car)
}
try? context.save()
}