iOS/코드조각

[iOS, Swift] CoreData CRUD 예제

검은참깨두유vm 2022. 12. 10. 18:17
반응형

iOS 16.1, Xcode 14.1, Swift 5, UIKit 환경에서 진행했습니다.

 

CREATE 생성코드

func createData(noteModel: NoteModel) {
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let context = appDelegate.persistentContainer.viewContext

    let entity = NSEntityDescription.entity(forEntityName: "Note", in: context)

    if let entity = entity {
        let note = NSManagedObject(entity: entity, insertInto: context)
        note.setValue(noteModel.memoIdx, forKey: "noteIdx")
        note.setValue(noteModel.content, forKey: "content")
        note.setValue(noteModel.regDate, forKey: "regDate")

        do {
          try context.save()
        } catch {
          print(error.localizedDescription)
        }
    }
}

 

READ 읽기코드

func readData() {
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let context = appDelegate.persistentContainer.viewContext

    do {
       let note = try context.fetch(Note.fetchRequest()) as! [Note]
       note.forEach {
           memoList.append(NoteModel(memoIdx: Int($0.noteIdx), content: $0.content, regDate: $0.regDate))
      }

    } catch {
       print(error.localizedDescription)
    }
}

 

UPDATE 수정코드

func updateData(at noteIdx: Int) {
    guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
    let managedContext = appDelegate.persistentContainer.viewContext
    let fetchRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest.init(entityName: "Note")
    fetchRequest.predicate = NSPredicate(format: "noteIdx = %@", "\(noteIdx)")

    do {
        let test = try managedContext.fetch(fetchRequest)
        let objectUpdate = test[0] as! NSManagedObject
        objectUpdate.setValue(contentTextView.text, forKey: "content")
        do {
            try managedContext.save()
        } catch {
            print(error)
        }
    } catch {
        print(error)
    }
}

 

DELETE 삭제코드

func deleteData(at noteIdx: Int) {
    guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
    let managedContext = appDelegate.persistentContainer.viewContext
    let fetchRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest.init(entityName: "Note")
    fetchRequest.predicate = NSPredicate(format: "noteIdx = %@", "\(noteIdx)")

    do {
        let test = try managedContext.fetch(fetchRequest)
        let objectToDelete = test[0] as! NSManagedObject
        managedContext.delete(objectToDelete)
        do {
            try managedContext.save()
        } catch {
            print(error)
        }
    } catch {
        print(error)
    }
}
반응형