我目前正在尝试使用 Core Data 来获取项目并将其添加到我的 UITableView 中。获取和添加项目工作正常。然而,问题是当数据没有任何内容时,我的获取结果是“ fatal error :在展开可选值时意外发现 nil”,这是有道理的,因为我数据库中没有任何内容。但我不想崩溃,而是想捕获错误并生成 UIAlert 错误消息而不是崩溃。但我当前的代码似乎不起作用。
func fetch() {
let itemsFetch = NSFetchRequest<NSFetchRequestResult>(entityName: "Items")
do {
let fetchedItem = try moc.fetch(itemsFetch) as! [Items]
self.itemsName.append(fetchedItem.first!.name!)
self.itemDate.append(fetchedItem.first!.date!)
self.tableView.reloadData()
//print(fetchedItem.first!.name!)
//print(fetchedItem.first!.date!)
} catch {
//I thought this statement would catch the error, but it
// is not doing that
print("Hello")
fatalError("Bad things happened \(error)")
}
}
更新 - 我已经更新了代码以检查 nil,但是,我得到:条件绑定(bind)的初始化程序必须具有可选类型,而不是 NSFetchRequest
。不知道如何解决。
func fetch() {
if let itemsFetch = NSFetchRequest<NSFetchRequestResult>(entityName: "Items") {
do{
let fetchedItem = try moc.fetch(itemsFetch) as! [Items]
self.itemsName.append(fetchedItem.first!.name!)
self.itemDate.append(fetchedItem.first!.date!)
self.tableView.reloadData()
//print(fetchedItem.first!.name!)
//print(fetchedItem.first!.date!)
} catch {
print("Hello")
fatalError("Bad things happened \(error)")
}
} else {
print("Checked")
}
}
最佳答案
您还可以使用
if !(itemsFetch.isEmpty){
}
else{
print("error")
}
关于ios - 使用核心数据获取零项会导致错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41390832/