简介
上下文:
我正在编写我的第一个应用程序,我希望能够在索引 0 处按下按钮时添加新行(请参阅下面的代码)。我使用 Realm 数据库来存储我的数据。
问题
- 按下添加按钮,我触发了以下崩溃
由于未捕获的异常“NSInternalInconsistencyException”而终止应用程序,原因:“尝试将第 0 行插入第 0 部分,但更新后第 0 部分中只有 0 行'.
- 此外,当我检查 tableView 数据数组
eventArray
的打印语句时,它始终为零。这让我相信我实际上并没有成功地将数据保存到 Realm 。
问题:
为什么数据没有保存到我的 Realm 数据库中?为什么我的 tableView 无法插入新行?
代码
我已经评论了我的问题发生的地方
class EventsScreen: UIViewController {
let realm = try! Realm()
var eventArray : EventList?
@objc func addEvent() { //The function my add button calls when pressed
let newCell = Event()
print(realm.objects(EventList.self).first)
insertInRealmContainerAtIndexZero(newEvent: newCell)
print(realm.objects(EventList.self).first)
let ndxPath = IndexPath(row: 0, section: 0)
tableView.beginUpdates()
tableView.insertRows(at: [ndxPath], with: .bottom) //App terminates on this line
tableView.endUpdates()
}
override func viewDidLoad() {
super.viewDidLoad()
loadEvents()
setupBackgroundVisuals()
registerCellAndDelegateAndDataSource()
}
private func insertInRealmContainerAtIndexZero(newEvent: Event) { // I suspect this method is the problem since when I restart the app the tableview doesn't load up any new created events.
if eventArray?.events != nil {
do {
try realm.write {
eventArray?.events.insert(newEvent, at: 0)
}
} catch {
print(error)
}
} else {
do {
try realm.write {
realm.add(newEvent)
}
} catch {
print(error)
}
}
}
private func loadEvents() {
eventArray = realm.objects(EventList.self).first
tableView.beginUpdates()
tableView.endUpdates()
}
}
数据对象:
class Event: Object {
@objc dynamic var eventTitle: String?
@objc dynamic var eventText: String?
}
class EventList: Object {
let events = List<Event>()
}
感谢您阅读我的帖子。
最佳答案
您第一次启动该应用程序时
eventArray = realm.objects(EventList.self).first
返回 nil,运行时返回
if eventArray?.events != nil {
它会转到 else ,因为 eventArray
是 nil ,然后在 else 中执行
realm.add(newEvent)
尽管你应该这样做
eventArray = EventList()
eventArray.events.append(newEvent)
然后添加
realm.add(eventArray)
关于ios - Swift:插入新行时,将 `List` 对象保存到 Realm 数据库以及随后的 tableView 更新时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51703757/