致命错误:在实体内部展开Optional值时意外发现nil

时间:2016-03-18 00:58:14

标签: ios swift core-data uicollectionview

我希望在点击删除按钮时删除UICollectionViewCell:

@IBAction func deleteButtonClicked() {

    error here:    delegate?.deleteTrigger(clothes!)

}

衣服:

var clothes: Clothes? {
        didSet {

            updateUI()
        }
    }

func deleteTrigger:

 func deleteTrigger(clothes: Clothes){

        let appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

        let context: NSManagedObjectContext = appDel.managedObjectContext!
        let en = NSEntityDescription.entityForName("Category", inManagedObjectContext: context)


        if let entity = NSEntityDescription.entityForName("Category", inManagedObjectContext: context) {



        let indexPath = NSIndexPath()

        //var cat : Category = clothing as! Category
        let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        let managedContext: NSManagedObjectContext = appDelegate.managedObjectContext!
        let fetchRequest = NSFetchRequest(entityName: "Clothes")

        let predicate = NSPredicate(format: "category == %@", self.selectedCategory!)
        fetchRequest.predicate = predicate

        var error: NSError? = nil
        var clothesArray = managedContext.executeFetchRequest(fetchRequest, error: &error)!
        managedContext.deleteObject(clothesArray[indexPath.row] as! NSManagedObject)
        clothesArray.removeAtIndex(indexPath.row)
        self.collectionView?.deleteItemsAtIndexPaths([indexPath])

        if (!managedContext.save(&error)) {
            abort()


        }

        }

服装是核心数据中的一个实体。有谁知道我为什么会收到这个错误?我试图以一对多的关系从核心数据中删除collectionViewCell。类别是父实体,服装是类别中的实体。

2 个答案:

答案 0 :(得分:1)

您已声明属性clothes

var clothes: Clothes?

您从未向其提供任何,因此它是nil。因此,当您通过说clothes!强行解开它时,就会崩溃。

答案 1 :(得分:0)

正如其他人所说,你的价值是零。您需要先解开变量,然后才能对其执行任何操作。试试这个:

@IBAction func deleteButtonClicked() 
{
  if var clothes = clothes
  {
    delegate?.deleteTrigger(clothes)
  }
}