2016-12-30 68 views
0

我目前正在尝试使用核心数据来获取项目并将其添加到我的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") 
     } 
    } 
+0

把此行中,如果条件一样,如果让itemsFetch = NSFetchRequest (的entityName: “项目”){} –

+0

检查'nil'访问之前,不像java swift不会抛出'NullPointerException' –

+0

@HimanshuMoradiya当我尝试这种方法,我得到2错误,使用未解决的标识符'itemsFetch'和条件绑定的初始化必须有可选类型,而不是NSFetchRequest –

回答

0

您还可以使用

if !(itemsFetch.isEmpty){ 
} 
else{ 
print("error") 
} 
0

好吧所以我找到了一个解决方案。这个问题来自do声明。以下是如何解决它。

let itemsFetch = NSFetchRequest<NSFetchRequestResult>(entityName: "Items") 

     do{ 
      let fetchedItem = try moc.fetch(itemsFetch) as! [Items] 
      if fetchedItem.count == 0{ 
       // Since i casted it to an array of items (my entity), 
       // I can check whether there are no data by checking 
       // if the length of the array is 0 
       print("Checked") 
      } 
      else{ 
       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)") 
     }