2017-02-16 37 views
0

時,我儘量讀字符串並寫入單元格,從核心數據,我得到以下錯誤致命錯誤意想不到的無核心數據

"fatal error: unexpectedly found nil while unwrapping an Optional value"

保存

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 
} 

和的tableView

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 
} 
+0

cell.nazwaLabel.text = nameTab [indexPath.row] as!字符串 –

+0

你能解釋一下嗎?在你的代碼崩潰 –

+0

@Lalit Kuma值2 = liczby.value(forKey:「nazwa」)!字符串在這我得到「exc_bad_instruction」 – k0le

回答

0

使用下面的代碼。你的代碼崩潰是因爲它從liczby [「nazwa」]獲取nil值或者是String以外的其他類型的值。

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

謝謝,工作! :) – k0le

+0

Em,我有另一個問題,我怎麼現在可以在tableView上顯示它?代碼就像主題 – k0le

+0

顯示一些「默認值」或不追加'nazwaTab'。所以,你將只包含單元格的值可用 –