我有一个使用 SwiftUI 构建的相当简单的应用程序,它本质上是一个主细节类型。数据存储在核心数据中。添加和更新记录工作正常,但从列表视图中删除项目时应用程序总是崩溃。我正在使用 .onDelete 修饰符进行删除。我没有收到任何错误消息 - 只是线程中断。记录确实被删除了,所以我猜测列表视图的重新渲染没有接收到更新的数据。
我可能在做梦,但我很确定删除功能在前两个 Beta 中有效。该应用程序仅在设备上运行。它在预览版和模拟器中都不起作用。
iOS 13.1、Xcode (11392r)、Catalina (19A546d)
这是 ContentView():
struct ContentView: View {
@Environment(\.managedObjectContext) var managedObjectContext
@FetchRequest(fetchRequest: ToDoItem.getAllToDoItems()) var toDoItems: FetchedResults<ToDoItem>
@State private var newToDoItem = ""
var body: some View {
NavigationView {
List {
Section(header: Text("Records")) {
ForEach(self.toDoItems) { toDoItem in
NavigationLink(destination: EditToDo(toDoItem: toDoItem)) {
ToDoItemView(title: toDoItem.title!,
firstName: toDoItem.firstName!,
lastName: toDoItem.lastName!,
//createdAt: "\(toDoItem.createdAt!)")
createdAt: self.localTimeString(date: toDoItem.createdAt!)
)
}
}
.onDelete { indexSet in
let deleteItem = self.toDoItems[indexSet.first!]
self.managedObjectContext.delete(deleteItem)
do {
try self.managedObjectContext.save()
} catch {
print(error)
}
}
.onMove(perform: move)
}
}
.navigationBarTitle("Customers")
.navigationBarItems(trailing: EditButton())
}
}
func move(from source: IndexSet, to destination: Int) {
print("this is the move method with no actions")
}
func localTimeString(date: Date) -> String {
let formatter = DateFormatter()
formatter.timeZone = .current
formatter.dateFormat = "M-d-yyyy HH:mm:ss"
let returnString = formatter.string(from: date)
return returnString
}//localTimeString
}
和托管对象:
public class ToDoItem : NSManagedObject, Identifiable {
@NSManaged public var id: UUID
@NSManaged public var createdAt: Date?
@NSManaged public var title: String?
@NSManaged public var firstName: String?
@NSManaged public var lastName: String?
}
extension ToDoItem {
static func getAllToDoItems() -> NSFetchRequest<ToDoItem> {
let request: NSFetchRequest<ToDoItem> = ToDoItem.fetchRequest() as! NSFetchRequest<ToDoItem>
let sortDescriptor = NSSortDescriptor(key: "createdAt", ascending: true)
request.sortDescriptors = [sortDescriptor]
return request
}
}
任何指导将不胜感激。