1

I'm trying to use core data with my table view elements, but I get a runtime error: "unexpectedly found nil while unwrapping an Optional value"

here is the cellForRowAtIndexPath function and the function for maintaining the core data, I'm not sure which part of these has the error

   func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = self.tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! itemsList


        let shopList = people[indexPath.row]
        cell.items!.text = shopList.valueForKey("name") as? String


        return cell
    }

func saveName(name: String) {
    //1
    let appDelegate =
        UIApplication.sharedApplication().delegate as! AppDelegate

    let managedContext = appDelegate.managedObjectContext

    //2
    let entity =  NSEntityDescription.entityForName("ShopList",
                                                       inManagedObjectContext:managedContext)

    let shopList = NSManagedObject(entity: entity!,
                                   insertIntoManagedObjectContext: managedContext)

    //3
        shopList.setValue(name, forKey: "name")

    //4
    do {
        try managedContext.save()
        //5
        people.append(shopList)
    } catch let error as NSError  {
        print("Could not save \(error), \(error.userInfo)")
    }
    }


override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)

    //1
    let appDelegate =
        UIApplication.sharedApplication().delegate as! AppDelegate

    let managedContext = appDelegate.managedObjectContext

    //2
    let fetchRequest = NSFetchRequest(entityName: "ShopList")

    //3
    do {
        let results =
            try managedContext.executeFetchRequest(fetchRequest)
        people = results as! [NSManagedObject]


    } catch let error as NSError {
        print("Could not fetch \(error), \(error.userInfo)")
    }
}

}

the breakpoint at this line

let managedContext = appDelegate.managedObjectContext
Reinier Melian
  • 18,995
  • 3
  • 32
  • 51
Afnan Humdan
  • 195
  • 3
  • 12

0 Answers0