CoreData 如何将项目添加到与实体相关的 NSSet

CoreData how to add items to a NSSet which is related to an entity

在我的项目中,我创建了两个实体:ContainerItems。两者之间是一对多的关系。在 Container 中,我调用了关系项并将其设置为“To Many”,因为我想在每个容器中包含很多项。在 Items 中,我调用了关系容器并将其设置为“To One”,因为每个项目都必须关联到一个容器。

除此之外,在我的项目中,我有一个表格视图,我可以在其中添加新容器,当我按下一个单元格时,我可以看到它的项目。创建容器的代码很好。当我尝试创建项目时出现问题:它们已成功创建,但它们出现在每个容器中。

在接下来的部分中,我将 post 对象、如何保存容器以及如何保存项目:

extension Container {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<Container> {
        return NSFetchRequest<Container>(entityName: "Container")
    }

    @NSManaged public var name: String?
    @NSManaged public var index: Int64
    @NSManaged public var items: NSSet?

}

extension Items {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<Items> {
        return NSFetchRequest<Items>(entityName: "Items")
    }

    @NSManaged public var text: String?
    @NSManaged public var image: UIImage?
    @NSManaged public var index: Int64
    @NSManaged public var container: Container?

}
let containerEntity = NSEntityDescription.entity(forEntityName: "Container", in: managedContext)!
        
        let items: NSSet = []
        
        let container = NSManagedObject(entity: containerEntity, insertInto: managedContext) as! Container
        
        ///Count is just an int variable
        container.setValue("Name", forKeyPath: "name")
        container.setValue(count, forKeyPath: "index")
        container.setValue(items, forKey: "items")
        
        do {
            try managedContext.save()

        } catch let error as NSError {
            print("Could not save. \(error), \(error.userInfo)")
        }
  let itemEntity = NSEntityDescription.entity(forEntityName: "Items", in: managedContext)!
        
        let items = NSManagedObject(entity: itemEntity, insertInto: managedContext) as! Items
 
        items.setValue("item", forKeyPath: "text")
        items.setValue(count, forKeyPath: "index")
     
        
        do {
            try managedContext.save()

        } catch let error as NSError {
            print("Could not save. \(error), \(error.userInfo)")
        }
        

无论如何,我认为与其创建项目实体,不如编辑容器实体,向其添加项目。为此,我尝试了这个,但我觉得我错过了一些东西,因为它崩溃了。

let fetchRequest:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest.init(entityName: "container")
       
       do {
           let test = try managedContext.fetch(fetchRequest)
           
           let objectUpdate = test[containerIndex] as! NSManagedObject
           
           objectUpdate.setValue("item", forKey: "text")
           objectUpdate.setValue(count, forKey: "index")
           
           do{
               try managedContext.save()
           } catch {
               print(error)
           }
          
       }
       catch {
           print(error)
       }

那么如何将项目添加到特定容器?

另外,如果我的两个实体属性被称为索引可以吗?

如果设置正确,应该会有 addToItems()

anyContainerObject.addToItems(value: Items)

只要您在核心数据模型中正确设置了反向关系,最简单的方法就是将相关的 Container 实例分配给新的 Itemcontainer 属性。核心数据将负责为您更新 Container 的一组 Item

let itemEntity = NSEntityDescription.entity(forEntityName: "Items", in: managedContext)!
        
let items = NSManagedObject(entity: itemEntity, insertInto: managedContext) as! Items
 
items.setValue("item", forKeyPath: "text")
items.setValue(count, forKeyPath: "index")
items.setValue(container, forKeyPath: "container")

do {
    try managedContext.save()
} catch let error as NSError {
    print("Could not save. \(error), \(error.userInfo)")
}

如果您使用为您的核心数据实体自动创建的对象,您的代码将更简单、更易于维护

        
let items = Item(context:managedObjectContext)
 
items.text = item
items.count = index
items.container = container

do {
    try managedContext.save()
} catch let error as NSError {
    print("Could not save. \(error), \(error.userInfo)")
}