我目前正在尝试使用核心数据来获取项目并将其添加到我的UITableView。抓取和添加项目工作正常。但是,问题是数据什么都没有,我的读取结果是“致命错误:在解包可选值时意外发现零”,这是有道理的,因为我在数据库中没有任何东西。但是,我不想崩溃,我想捕捉错误并产生一个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)")
}
}
更新 - 我已经更新了代码来检查为零,但是,我得到:Initialiser for conditional binding must have optional type not 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")
}
}
把此行中,如果条件一样,如果让itemsFetch = NSFetchRequest(的entityName: “项目”){} –
检查'nil'访问之前,不像java swift不会抛出'NullPointerException' –
@HimanshuMoradiya当我尝试这种方法,我得到2错误,使用未解决的标识符'itemsFetch'和条件绑定的初始化必须有可选类型,而不是NSFetchRequest –