ios - SwiftUI .onDelete 的 List 视图崩溃 App
问题描述
我有一个使用 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
}
}
任何指导将不胜感激。
解决方案
这似乎令人难以置信,但显然将实体中的属性命名为“id”是这种行为的原因。我将 UUID 属性的名称更改为“myID”,现在可以删除。在进行更改之前,我将 Xcode 更新为 GM 种子 2(在重命名之前,崩溃仍然发生在 GM2 中)。列表视图在预览中仍然完全不起作用,但它现在可以在模拟器和设备中使用。
推荐阅读
- javascript - 弹出窗口总是显示相同的数据
- android - 为什么当我的应用程序关闭时我没有收到 FCM 通知?
- xml - 在 xquery 中根据输出是否格式正确使用 fn:parse-xml()
- kubernetes - Kubernetes 集群 v1.19.4 中处于待处理状态的 Coredns
- c# - 如果功能由按钮触发,WPF 绑定不起作用
- javascript - 反应:TypeError:无法读取 null 的属性“菜”
- android - 作为吗?在 if 语句中确保块内的实例在所有 if 块内都不为空?
- python - 在 Pyspark Dataframes 上左连接和应用案例逻辑
- arrays - p / primes[i] >= primes[i] 背后的逻辑,同时使用数组查找素数
- flask - @app.before_request 中的 Flask 重定向调用会破坏所有 .css 和 .js