【发布时间】:2020-09-09 20:04:51
【问题描述】:
我一直在尝试遵循 Realm Swift 团队提供的 ListSwiftUI 示例。它对我来说一直很好,但是我遇到了一个问题,当我尝试从 RealmSwift.List<Object> 中删除时,应用程序崩溃并出现异常 "Terminating app due to uncaught exception 'RLMException', reason: 'Index 5 is out of bounds (must be less than 5).'"
型号:
final class Todo: Object, ObjectKeyIdentifiable {
@objc dynamic var id: String = UUID().uuidString
@objc dynamic var name: String = ""
@objc dynamic var createdAt: Date = Date()
override class func primaryKey() -> String? {
"id"
}
}
final class Todos: Object {
@objc dynamic var id: Int = 0
let todos = List<Todo>()
override class func primaryKey() -> String? {
"id"
}
}
SceneDelegate.swift
let realm = try! Realm()
var todos = realm.object(ofType: Todos.self, forPrimaryKey: 0)
if todos == nil {
todos = try! realm.write { realm.create(Todos.self, value: []) }
}
// Create the SwiftUI view that provides the window contents.
let contentView = ContentView(todos: todos!.todos)
ContentView.swift
@ObservedObject var todos: RealmSwift.List<Todo>
var body: some View {
ForEach(todos) { (todo: Todo) in
Text("\(todo.name)")
.onDelete(perform: delete)
}
func delete(at offsets: IndexSet) {
if let realm = todos.realm {
try! realm.write {
realm.delete(todos[offsets.first!])
}
} else {
todos.remove(at: offsets.first!)
}
}
我已经检查了我的待办事项列表的计数和 Realm Studio 中的数据库,它实际上包含索引 5。而且这个崩溃不仅仅针对索引 5,例如如果列表中只有 2 个项目,应用程序会因Index 1 而崩溃,或者当它包含 5 个项目时,应用程序会因Index 4 而崩溃。
该示例具有几乎相同的数据模型,并且可以完美运行。那么我在这里做错了什么?
【问题讨论】:
标签: ios swift database xcode realm