/CoreData-Combine

Create CoreData byCombine

Primary LanguageSwift

CoreDataExample

We learn how to save entity, delete or fetch from CoreData by Combine

Save

 private func addPerson() {
      let action: Action = {
          let bezo: Person = coreDataStore.createEntity()
          bezo.first_name = "Bezo"
          bezo.last_name = "Deda"

          let volksCar: Car = coreDataStore.createEntity()
          volksCar.name = "Volkswagen"
          volksCar.owner = bezo

          let bmwCar: Car = coreDataStore.createEntity()
          bmwCar.name = "BMW"
          bmwCar.owner = bezo

          bezo.cars = [volksCar, bmwCar]
      }

      coreDataStore
          .publicher(save: action)
          .sink { completion in
              if case .failure(let error) = completion {
                  message = error.localizedDescription
              }
          } receiveValue: { success in
              if success {
                  message = "Saving entities succeeded"
                  number_of_persons += 1
              }
          }
          .store(in: &bag)
  }

Fetch

private func fetchPersons() {
        let request = NSFetchRequest<Person>(entityName: Person.entityName)
        coreDataStore
            .publicher(fetch: request)
            .sink { completion in
                if case .failure(let error) = completion {
                    message = error.localizedDescription
                }
            } receiveValue: { persons in
                message = "Fetching entities succeeded"
                number_of_persons = persons.count
            }
            .store(in: &bag)
    }

Delete

  private func deleteAllPersons() {
        let request = NSFetchRequest<NSFetchRequestResult>(entityName: Person.entityName)
        request.predicate = NSPredicate(format: "first_name LIKE[cd] %@", "Deda")
        coreDataStore
            .publicher(delete: request)
            .sink { completion in
                if case .failure(let error) = completion {
                    message = error.localizedDescription
                }
            } receiveValue: { _ in
                message = "Deleting entities succeeded"
                number_of_persons = 0
            }
            .store(in: &bag)
        
    }