DEV Community

Discussion on: How to make a task list using SwiftUI and Core Data

 
maeganwilson_ profile image
Maegan Wilson • Edited

Here's a branch of the original project with what you're looking to do that's been implemented.

Create a new file with the functions like this one linked here.

In the ContentView.struct file, add let core_data_helper = CoreDataHelper(). Then in the button's actions, call the functions from core_data_helper.

Here's an example of addTask():

Button(action: {
    self.core_data_helper.addTask(self.taskName, context: self.context)
}){
    Text("Add Task")
}

Here's a link to what ContentView.swift should look like.

Thread Thread
 
cpiersigilli profile image
Cesare Piersigilli

Great solution. But, wanting to move from ContentView to CoreDataHelper:
@Environment(.managedObjectContext) var context
and
@FetchRequest(
entity: Task.entity(),
sortDescriptors: [NSSortDescriptor(keyPath: \Task.dateAdded, ascending: false)],
predicate: NSPredicate(format: "isComplete == %@", NSNumber(value: false))
) var notCompletedTasks: FetchedResults
How can it be done?
It's possible?
Thank you.

Thread Thread
 
maeganwilson_ profile image
Maegan Wilson

You can, but the @Environment and @FetchRequest are used with SwiftUI views. I wouldn't move the @Environment to make sure that there is a context associated with the view. I also like to leave my FetchRequests in the view because that's where I need the data to be viewed.

Thread Thread
 
cpiersigilli profile image
Cesare Piersigilli

Your explanation convinced me. Thank you.