CordData 사용해보기

태그: 

2 답변 글타래를 보이고 있습니다
  • 글쓴이
    • 은지짱
      참가자
      • 글작성 : 13
      • 답글작성 : 7

      TodoList using coredata

      coredata 를 사용한 todo list app 을 만들어보자

      1. Project setting

      Use Core Data 를 체크하면 xcdatamodeld 파일이 디렉토리에 생성됨을 확인할 수 있다.

       

      1. Data Setting

      데이터 모델에 원하는 entity 와 attribute, type 을 지정한다
      entity 가 하나의 구성 요소, 모델의 역할을 한다.

       

      1. Save Data
      import CoreData
      
      var itemName: [NSManagedObject] = [] // todolist의 coredata 배열
      
      func save(alert: UIAlertAction!){
      let appDelegate = UIApplication.shared.delegate as! AppDelegate
      let context = appDelegate.persistentContainer.viewContext
      let entity = NSEntityDescription.entity(forEntityName: "Title", in: context)!
      let theTitle = NSManagedObject(entity: entity, insertInto: context)
      theTitle.setValue(titleTextField.text, forKey: "title") // attribute
      
      do {
      try context.save()
      itemName.append(theTitle)
      } catch {
      print("There was a error in saving..")
      }
      self.tableView.reloadData()
      }
      
      

      context 를 통해 간접적으로 접근한다.

       

      1. Remove Data
      func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
      if editingStyle == UITableViewCell.EditingStyle.delete {
      let appDelegate = UIApplication.shared.delegate as! AppDelegate
      let context = appDelegate.persistentContainer.viewContext
      context.delete(itemName[indexPath.row])
      itemName.remove(at: indexPath.row)
      
      do{
      try context.save()
      }catch {
      print("There was a error in deleting")
      }
      }
      self.tableView.reloadData()
      }
      
      1. Load Data (Fetch)
      override func viewWillAppear(_ animated: Bool) {
      super.viewWillAppear(animated)
      
      let appDelegate = UIApplication.shared.delegate as! AppDelegate
      let context = appDelegate.persistentContainer.viewContext
      let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Title")
      
      do {
      itemName = try context.fetch(fetchRequest)
      } catch {
      print("Error in loading data")
      }
      }
      

      • 이 게시글은 은지짱에 의해 3 years, 11 months 전에 수정됐습니다.
      • 이 게시글은 은지짱에 의해 3 years, 11 months 전에 수정됐습니다.
    • 야곰
      키 마스터
      • 글작성 : 37
      • 답글작성 : 580

      @choieunji0114
      대체로 모든 글이 깨져있고, 대부분의 글에 대한 답변에도 본인의 피드백이 없네요.
      사이트 사용에 어려움을 겪고 계신가요? 도와드릴 부분이 있을까요?
      어려움을 겪고계신 부분이 있다면 피드백 주시면 감사하겠습니다.

    • 은지짱
      참가자
      • 글작성 : 13
      • 답글작성 : 7

      사이트 사용이 익숙하지 않아서 글이 많이 깨졌습니다 ..

      빠른 시일 내에 수정하도록 하겠습니다!! ㅠㅠ

2 답변 글타래를 보이고 있습니다
  • 답변은 로그인 후 가능합니다.

logo landscape small

사업자번호 : 743-81-02195
통신판매업 신고번호 : 제 2022-충북청주-1278 호
고객센터 : 카카오톡채널 @yagom