2016-03-18 61 views
0

我希望在删除按钮被窃听的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。类别是父实体,而衣服是类别内的实体。

+0

你是说'代表.deleteTrigger(衣服!)' - 你用一个感叹号任何时候,你乞讨崩溃?这就是Swift中感叹号_means_。你确实崩溃了。没有什么大惊喜。如果你不想,不要这样做。 – matt

回答

0

正如其他人所说,你的价值为零。你需要先解开变量,然后才能对它做任何事情。试试这个:

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

你声明的属性clothes

var clothes: Clothes? 

你从来没有给它的任何,所以它是nil。因此,当您通过说clothes!强制展开它时,就会崩溃。

+0

当我换衣服时,仍然出现同样的错误:衣服?去衣服:衣服!当我改变委托?.deleteTrigger(衣服!)委托?.deleteTrigger(衣服)@matt –

+0

这并不令我感到惊讶。你是_still_不给这个变量任何值。你所做的只是移动感叹号。 – matt

相关问题