Skip to content

Instantly share code, notes, and snippets.

@donchan922
Created April 11, 2020 23:15
Show Gist options
  • Save donchan922/ff7626e55a3598cae18b0a049cabe5ec to your computer and use it in GitHub Desktop.
Save donchan922/ff7626e55a3598cae18b0a049cabe5ec to your computer and use it in GitHub Desktop.
SwiftUIでCore Dataを使ったToDoアプリのサンプルコード
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)
}
}
@donchan922
Copy link
Author

donchan922 commented Apr 11, 2020

事前準備

  • プロジェクトを作成する際、「Use Core Data」にチェックを入れる
  • 「xxx.xcdatamodel」を開き、以下を行う
    • ENTITIESに「Task」を新規追加
    • Attributesに以下を追加
      • id: UUID
      • name: String
      • isComplete: Boolean
      • dateAdded: Date

参考リンク

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment