swift Core Data“对多”关系将对象保存在字典中,而不是保存在集合中

zy1mlcev  于 2023-01-29  发布在  Swift
关注(0)|答案(1)|浏览(135)

我正在使用Core Data,并且一直在使用这个hackingWithSwift教程。我有两个具有一对多关系的实体。
1.国家实体

extension Country {

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

    @NSManaged public var id: UUID?
    @NSManaged public var fullName: String?
    @NSManaged public var shortName: String?
    @NSManaged public var candy: NSSet?
    
    public var wrappedShortName: String {
        shortName ?? "Unknown Country"
    }
    
    public var wrappedFullName: String {
        fullName ?? "Unknown Country"
    }
    
    public var candyArray: [Candy] {
        let set = candy as? Set<Candy> ?? []

        return set.sorted {
            $0.wrappedName < $1.wrappedName
        }
    }

}

// MARK: Generated accessors for candy
extension Country {
    
    @objc(addCandyObject:)
    @NSManaged public func addToCandy(_ value: Candy)

    @objc(removeCandyObject:)
    @NSManaged public func removeFromCandy(_ value: Candy)

    @objc(addCandy:)
    @NSManaged public func addToCandy(_ values: NSSet)

    @objc(removeCandy:)
    @NSManaged public func removeFromCandy(_ values: NSSet)
}

1.糖果实体

extension Candy {
    
    @nonobjc public class func fetchRequest() -> NSFetchRequest<Candy> {
        return NSFetchRequest<Candy>(entityName: "Candy")
    }
    
    @NSManaged public var id: UUID?
    @NSManaged public var name: String?
    @NSManaged public var origin: Country?
    
    public var wrappedName: String {
        name ?? "Unknown Candy"
    }
}

所以乡村可以有很多糖果。
我想知道的是,当我创建一个Candy并保存它时,是否有可能不将其添加到Country实体中的Candy的NSSet中,而是将其保存到NSDictionary或除NSSet之外的任何其他集合类型中?不确定我是否只是更改

@objc(addCandy:)
    @NSManaged public func addToCandy(_ values: NSSet) //Change to NSDictionary

    @objc(removeCandy:)
    @NSManaged public func removeFromCandy(_ values: NSSet) //Change to NSDictionary

如果这工作,因为我想实体id属性是键和对象的价值。不知道这是否可能。
这就是它们的添加方式

let candy3 = Candy(context: viewContext)
                    candy3.name = "Twix"
                    candy3.orgin = Country(context: viewContext)
                    candy3.orgin?.shortName = "UK"
                    candy3.orgin?.fullName = "United Kingdom"

                    let candy4 = Candy(context: viewContext)
                    candy4.name = "Toblerone"
                    candy4.orgin = Country(context: viewContext)
                    candy4.orgin?.shortName = "CH"
                    candy4.orgin?.fullName = "Switzerland"

                    try? viewContext.save()

如果这不合理请提问。

lb3vh1jj

lb3vh1jj1#

可以将Transformable用于encode,将decode用于Dictionary,但不能将关系更改为字典

相关问题