2016-11-07 31 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

会做。再次感谢。 –