1

I am starting to work on Core Data applications with SwiftUI. I have a view that looks like this:

struct ContentView: View {
 @FetchRequest(sortDescriptors: []) private var todoItems: FetchedResults<TodoItem>
 enter code here
 var body: some View {
 List(todoItems) { todoItem in
 Text(todoItem.title)
 }
 }
}

This works and I can display all the todo items on the screen. But now my view is tightly coupled with Core Data. What if in the future, the client decides that they want to use Realm or GRDB?

Should I separate out my data access layer completely?

But if I do that then I would not be able to use all the property wrappers for Core Data that are available for SwiftUI like @FetchRequest and @SectionedFetchedRequest.

How would you handle such situation?

Alexander
5,1951 gold badge24 silver badges28 bronze badges
asked Jul 15, 2023 at 3:41

1 Answer 1

1

Not only does your view depend on the data layer, but the data layer also depends on the view.

The simplest method to separate it properly is MVC or model-view-controller: You have a model class which gathers your data, by any means it likes. You have your view class which displays data, wherever it comes from. And you have a controller class, which asks the model what data is there, tells the view what to display, gets told by the view what actions to take and passes that to the model.

The model doesn’t even know there is a view. The view doesn’t even know there is a model. The controller has interfaces for model and view but has no idea how they do their job.

answered Jul 16, 2023 at 11:30
1
  • Thanks! Do you recommend MVC to be used for SwiftUI framework? Commented Jul 20, 2023 at 22:54

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.