在使用核心数据展开Optional值时意外地发现了nil

时间:2016-06-08 23:29:15

标签: ios swift core-data nsfetchrequest

我试图将核心数据与我的表格视图元素一起使用,但是我收到了一个运行时错误:"在解开一个Optional值时出乎意料地发现了nil"

这里是cellForRowAtIndexPath函数和维护核心数据的函数,我不确定哪些部分有错误

   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)")
    }
}

}

此行的断点

let managedContext = appDelegate.managedObjectContext

0 个答案:

没有答案