10

I'm making progress learning SwiftUI but I'm getting stuck when it comes to using it with Core Data.

  • Model Objects - I made a couple of entities with the required properties and relationships
  • ??? I have no idea where to begin. How to I get SwiftUI talking to Core Data?
  • SwiftUI - I have some basic layouts working and showing data from some temp classes, but these have no awareness of Core Data

I've spend the last few days searching and reading everything I can on this topic but I have no idea how to begin to solve this.

Can anyone outline the basic steps to using Core Data with SwiftUI?

Update:

I got some additional feedback on Twitter and one dev suggested that SwiftUI lists may not be suitable for working with Core Data with large data sets. Read the post here: https://twitter.com/numist/status/1141012785825845248

Here is the approach I'm going to take in my app.

  • List Views:
    • UITableViewController (with a FetchedResultsController)
    • Manage the connection to Core Data store
    • Use dependency injection to pass records to a detail view
  • Detail / Edit Views:
    • When possible build these with UIHostingController
    • Use SwiftUI Forms to make simple data entry forms
    • Receive data via dependency injection
    • Copy data to a temporary BindableObject type
      • Make local UI chances to the temp record
      • Save the temp data back to the actual record on exit

Update 2 - 2019.08.14

Xcode beta 5 has some new Core Data features. I used the information in this blog post to get most of what I need.

2
  • Since there was no comment, I can only assume that my answer below was not appropriate for some reason, so I deleted it. If you are still looking for some hints and tips on how to use CoreData with SwiftUI and need a place to start, check out my answer to stackoverflow.com/questions/57348127/… Commented Aug 21, 2019 at 23:42
  • @ChuckH Sorry, I never even saw your answer. You sample project looks pretty awesome though. Commented Aug 22, 2019 at 17:46

1 Answer 1

6

You can write a wrapper for your Core-Data logic, like EntityManager and then use it inside BindableObject

class PersonStore: BindableObject {
  var didChange = PassthroughSubject<Void, Never>()

  var persons: [PersonEntity] = [] {
      didSet {
          didChange.send(())
      }
  }

  func fetchPersons(matching name: String) {
    // make you core data query here and assign it to persons property
  }
}

As soon as you query finish and value assigned to persons property SwiftUI will reload View to read new values.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.