CoreData

모든 엔티티(테이블 = class)들을 permanent storage에 저장 (Persistent Container)

Persistent Container

Persistent Container는 SQLite database이다.

모든 테이블과 테이블간 관계를 저장

context

일시적인 공간(temporary area), 중간 영역(intermediate area)

유저는 직접적으로 Persistent Container에 접근할 수 없기 때문에, CRUD를 context에서 진행

context에서 모든 작업을 완료한 후 저장

let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
...
try context.save() //commit!
...

git 과 유사하다. (작업을 완료 후, add, commit, push단계를 거친다)

NSManagedObject

every single row is individual NSManagedObject (inside tables)

Item(context: self.context)

Create

let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

let newItem = Item(context: self.context)
//what will happen once the user  clicks  the add items button on our uialert
if let text = textField.text {
    newItem.title = text
    newItem.done = false
    self.itemArray.append(newItem)
    self.savedItem()
}

//savedItem()
do {
    try context.save()
} catch {
    print("save error")
}

Read

대부분의 경우 데이터타입의 명시가 필수는 아니지만, request의 data type을 명시해줘야 한다.

var itemArray = [Item]()
...
func loadItems() {
		// 데이터 타입 생략시, Ambiguous (모호성) error
    let request : NSFetchRequest<Item> = Item.fetchRequest()
    
    do {
        itemArray = try context.fetch(request)
    } catch {
        print("Error fetching data from context \\(error)")
    }
}