본문 바로가기

이전 블로그 글

220617 TIL [CoreData 사용 방법 - 1(프로젝트 생성시 설정 및 create & read)] (블로그 이전 포스팅)

원문 링크

위와 같은 뷰를 구성해서 텍스트 필드에 문자 입력 후 `코어 데이터에 저장` 버튼을 누르면 코어데이터에 저장하고 `저장된 정보들 프린트` 를 하면 말 그대로 저장되어있는 정보들을 프린트 할 예정이다

1. 프로젝트 생성 코어 데이터 체크

(물론 체크해주지 않고 나중에 추가 해줄 수도 있음)

2. CoreData 세팅

일단 처음 생성시 파일 이름과 entites들이 비어있는데 이 부분 부터 먼저 수정해주자
(Add Entity 버튼을 통해 추가 가능)

그리고 inspector 부분에 Codegen이라는 항목이 있는데 이 중에서 `Manual/None` 을 선택한다
(세 가지 항목에 대한 차이 점은 따로 작성 예정)

Editor의 해당 선택지를 클릭 해 코어데이터에서 사용할 클래스를 만들어준다

그리고 변경해준 파일 명을 AppDelegate로 이동하여 수정해준다
(지금은 기본 설정대로 AppDelegate에 만들어졌는데 나중에 CoreDataManager라는 객체를 따로 만들어서 그곳에서 container를 만들어줘도 될듯)

3. 저장 및 불러오기
    1. textField 내용을 저장할 객체 만들기

    위와 같이 coredata에 저장될 모델을 만들고

textField에서 받아온 정보를 3-1에서 만든 모델 타입으로 반환 시켜주기

   2. save버튼을 통해 저장하기

@IBAction func touchSaveButton(_ sender: UIButton) {
        guard let textModel = getText() else { return }
        
        //NSManagedObjectContext가져오기 (현재는 appDelegate에 작성되어있으니 appDelegate 부터 가져오고 거기서 context가져오기
        guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
        let context = appDelegate.persistentContainer.viewContext
        
        //entity 가져오기 (forEntityName은 coredata model파일에서 만들어준 entity의 이름)
        guard let entity = NSEntityDescription.entity(forEntityName: "Text", in: context) else { return }
        
        //NSManagedObject 생성
        let text = NSManagedObject(entity: entity, insertInto: context)
        //NSManagedObject 값 세팅
        text.setValue(textModel.text, forKey: "text")
        text.setValue(textModel.count, forKey: "textCount")
        
        //NSManagedObjectContext에 저장하기
        do {
            try context.save()
        } catch {
            print(error.localizedDescription)
        }
    }

    3. print 버튼을 통해 정보 불러와 프린트 하기

@IBAction func touchPrintButton(_ sender: UIButton) {
        //NSManagedObjectContext가져오기 (현재는 appDelegate에 작성되어있으니 appDelegate 부터 가져오고 거기서 context가져오기
        guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
        let context = appDelegate.persistentContainer.viewContext
        
        //NSManagedObjectContext에서 data불러오기
        do {
            let texts = try context.fetch(Text.fetchRequest()) as [Text]
            for (index, text) in texts.enumerated() {
                print("\(index)-------------")
                print("text : \(text.text ?? "")")
                print("count : \(text.textCount)")
            }
        } catch {
            print(error.localizedDescription)
        }
    }

결과

참고자료
https://zeddios.tistory.com/987