我有一个使用SwiftUI构建的相当简单的应用程序,基本上是主细节类型。 数据存储在Core Data中。 添加和更新记录没有问题,但在从列表视图中删除项目时,应用程序总会崩溃。 我使用.onDelete修饰符进行删除。 我没有收到任何错误消息-只是线程中断。 记录确实被删除,因此我猜测列表视图的重新渲染没有接收到更新后的数据。
我可能是在做梦,但我非常确定删除功能在前两个Beta版中有效。 应用程序仅在设备上运行。 它无法在预览或模拟器中工作。
iOS 13.1,Xcode(11392r),Catalina(19A546d)
这是ContentView():
我可能是在做梦,但我非常确定删除功能在前两个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
}
还有managedObject:
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
}
}
希望能得到您的指导。
onDelete
调用它。移动代码后,请全部注释掉并逐行重新引入(在可能的情况下)。看看能否缩小事物范围。 - user7014451DispatchQueue.main.asyncAfter(deadline: .now() + 0.01)
,现在列表完美地工作了。 - KB-YYZonDelete
中拥有的所有代码放入延迟闭包中。我知道我的情况不同,但当前版本的列表存在时间问题。 - KB-YYZ