반응형
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)
}
}
반응형
'iOS > 코드조각' 카테고리의 다른 글
[iOS, Swift] json파일 struct 모델 형식으로 가져오기 (0) | 2023.01.22 |
---|---|
[iOS, Swift] Enum 타입 rawValue 값 등록하기 (0) | 2023.01.03 |
[iOS, Swift] CoreData 엔터티 생성 예제 (0) | 2022.12.10 |
[iOS, Swift] CoreData 초기 설정 안 해주었을 시 수동 설정방법 (0) | 2022.12.10 |
[iOS, Swift] 객체 메모리 주소 찾기2 (0) | 2022.12.02 |