2016-11-07 30 views
0

我正在描述Core Data圖中的一些顏色信息。該實體是一種顏色,屬性是顏色組件。如何刪除managedObject - 不是tableView

我在兩個方面掙扎:如何從圖形中刪除顏色對象,其次(獎金問題?),我怎麼能識別重複的顏色?

在我的AppDelegate,我有一個這樣的核心數據堆棧:

lazy var persistentContainer: NSPersistentContainer = { 

     let container = NSPersistentContainer(name: "DD") 
     container.loadPersistentStores(completionHandler: { (storeDescription, error) in 
      if let error = error as NSError? { 
       // Replacing this implementation with code to handle the error appropriately. 

       fatalError("Unresolved error \(error), \(error.userInfo)") 
      } 
     }) 
     return container 
    }() 

    // MARK: - Core Data Saving support 

    func saveContext() { 
     print(#function) 
     let context = persistentContainer.viewContext 
     if context.hasChanges { 
      do { 
       try context.save() 
      } catch { 
       // Replace this implementation with code to handle the error appropriately. 
       // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
       let nserror = error as NSError 
       fatalError("Unresolved error \(nserror), \(nserror.userInfo)") 
      } 
     } 
    } 

,並在那裏我試圖刪除的顏色,我有這樣的:

func deleteColor(_ sender:UIButton) { 

     let i : Int = (sender.layer.value(forKey: "index")) as! Int 
     print(#function, "object to delete: ", i) 

     let managedContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext 

     colors.remove(at: i) 

     do { 
      try managedContext.save() 
     } catch let error as NSError { 
      print("Error While Saving Data: \(error.userInfo)") 
     } 

     recentColorCollection!.reloadData()  
    } 

變量是:

var colors = [RecentColorEntity]() 
    var colorEntity = "RecentColorEntity" 

我沒有得到任何錯誤,但對象沒有被刪除..有人可以幫我弄清楚什麼我做錯了

回答

1
colors.remove(at: i) 

只是從內存中的顏色數組中刪除顏色。您需要刪除實際的物體,像這樣

context.delete(colorObject) 

並保存。

+0

謝謝先生!這就是訣竅!我會歡迎你的想法如何識別模糊(額外信貸..)謝謝 –

+0

您發佈了一個新問題。 – Mundi

+0

會做。再次感謝。 –