致命错误:在实体内解包可选值时意外发现 nil



我希望在点击删除按钮时删除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()

        }
        }

衣服是核心数据中的一个实体。 有谁知道为什么我会收到此错误? 我正在尝试从具有一对多关系的核心数据中删除集合ViewCell。 类别是父实体,衣服是类别中的实体。

您已声明属性clothes

var clothes: Clothes?

你从来没有给它任何价值,所以它nil.因此,当你通过说clothes!来强制打开它时,你会崩溃。

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

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

最新更新