【问题标题】:Fatal error unexpected nil core Data致命错误意外零核心数据
【发布时间】:2017-02-16 11:52:50
【问题描述】:

当我尝试读取字符串并写入单元格时,从核心数据中我得到以下错误

“致命错误:在展开 Optional 时意外发现 nil 价值”

保存

func getContext() -> NSManagedObjectContext {
    let appDelegate = UIApplication.shared.delegate as? AppDelegate
    return (appDelegate?.persistentContainer.viewContext)!
}

func save(value:String, forKey:String) {
    let context = getContext()
    let entity = NSEntityDescription.entity(forEntityName: "Ostatnie", in: context)

    let adj = NSManagedObject(entity: entity!, insertInto: context)
    add.setValue(value, forKey: forKey)

    do {
        try context.save()
        print("save - \(value)")
    } catch {
        print("err zapisu \(error)")
    }
}

保存

save(value: annotation.title!, forKey: "nazwa")

获取值(具有全局变量 nameTab:[String] = [])

func get(value:String ) -> String {
    var value2 = value
    let request: NSFetchRequest<Ostatnie> = Ostatnie.fetchRequest()

    do {
        let result = try getContext().fetch(request)

        for liczby in result {
            print(liczby.value(forKey: "nazwa") ?? String.self)
            value2 = liczby.value(forKey: "nazwa") as! String
            nazwaTab.append(wartosc2)
            print(nameTab)

            print(nameTab)
        }

    } catch {
        print(error)
    }
    return value2
}

和表格视图

 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return nazwaTab.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! cellTableViewCell

    cell.nazwaLabel.text = nameTab[indexPath.row]

    return cell
}

【问题讨论】:

  • cell.nazwaLabel.text = nameTab[indexPath.row] as!字符串
  • 你能解释更多吗?你的代码到底在哪一行崩溃了
  • @Lalit Kuma value2 = liczby.value(forKey: "nazwa") as!对此字符串我得到“exc_bad_instruction”
  • @SarabjitSingh 不工作:/

标签: ios iphone swift uitableview core-data


【解决方案1】:

使用下面的代码。您的代码崩溃是因为它要么从 liczby["nazwa"] 获得 nil 值,要么是 String 以外的其他类型的值。

if let str = liczby["nazwa"] as? String {
   value2 = str
}

【讨论】:

  • Em,我还有一个问题,我现在如何在tableView上显示它?类似主题的代码
  • 显示一些“默认值”或不附加nazwaTab。因此,您将只包含值可用的单元格
  • link 那是我的 tabvView,在 cellTableViewCell 上我只有网点
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-11
  • 1970-01-01
  • 1970-01-01
  • 2012-04-04
  • 2020-10-26
  • 2012-01-28
相关资源
最近更新 更多