Created
April 11, 2020 23:15
-
-
Save donchan922/ff7626e55a3598cae18b0a049cabe5ec to your computer and use it in GitHub Desktop.
SwiftUIでCore Dataを使ったToDoアプリのサンプルコード
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
import CoreData | |
struct ContentView: View { | |
@State private var taskName: String = "" | |
@Environment(\.managedObjectContext) var context | |
@FetchRequest( | |
entity: Task.entity(), | |
sortDescriptors: [NSSortDescriptor(keyPath: \Task.dateAdded, ascending: true)], | |
predicate: NSPredicate(format: "isComplete == %@", NSNumber(value: false)) | |
) var notCompletedTasks: FetchedResults<Task> | |
var body: some View { | |
VStack { | |
HStack { | |
TextField("Task Name", text: $taskName) | |
Button(action: { | |
self.addTask() | |
self.taskName = "" | |
}) { | |
Text("Add Task") | |
} | |
}.padding() | |
List { | |
ForEach(notCompletedTasks, id: \.self.id) { task in | |
Button(action: { | |
self.updateTask(task) | |
}) { | |
Text(task.name ?? "No name given") | |
} | |
} | |
} | |
} | |
} | |
func addTask() { | |
let newTask = Task(context: context) | |
newTask.id = UUID() | |
newTask.name = taskName | |
newTask.isComplete = false | |
newTask.dateAdded = Date() | |
do { | |
try context.save() | |
} catch { | |
print(error) | |
} | |
} | |
func updateTask(_ task: Task){ | |
let fetchRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "Task") | |
fetchRequest.predicate = NSPredicate(format: "id == %@", task.id! as NSUUID as CVarArg) | |
fetchRequest.fetchLimit = 1 | |
do { | |
let taskUpdate = try context.fetch(fetchRequest)[0] as! NSManagedObject | |
taskUpdate.setValue(true, forKey: "isComplete") | |
try context.save() | |
} catch { | |
print(error) | |
} | |
} | |
} | |
struct ContentView_Previews: PreviewProvider { | |
static var previews: some View { | |
let context = (UIApplication.shared.delegate as! AppDelegate) | |
.persistentContainer.viewContext | |
return ContentView().environment(\.managedObjectContext, context) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
事前準備
参考リンク