0
votes

When, I try read string and write into cell, from core data I get the following error:

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

save

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

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

get value (have global var 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
}

and 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
}
1
cell.nazwaLabel.text = nameTab[indexPath.row] as! StringSarabjit Singh
can you explain more. On exactly which line your code crashingLalit Kumar
@Lalit Kuma value2 = liczby.value(forKey: "nazwa") as! String on this I get "exc_bad_instruction"k0le
@SarabjitSingh not working :/k0le

1 Answers

0
votes

Use below code. Your code crashing is because either it is getting nil value from liczby["nazwa"] or value which is of other type than String.

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