Ordered List With Core Data

十年热恋 提交于 2019-12-04 06:53:57

问题


I am working with a class which is both NSManagedObject and Codable. It's a Feed and it has multiple Albums. I want the ordered list of Albums but Core Data forces me to use Set instead, which is not ordered. I can use NSOrderedSet, but it doesn't work well with Codable. What would be the best way to get the ordered list in Core Data. Below is the Model I am trying to make work.

public class Feed: NSManagedObject, Codable {

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

    @NSManaged public var title: String
    @NSManaged public var albums: Set<Album>
    @NSManaged public var feedContainer: FeedContainer?

    enum CodingKeys: String, CodingKey {
        case title
        case albums = "results"
        case feedContainer
    }

    public func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(title, forKey: .title)
        try container.encode(albums, forKey: .albums)
    }

    public required convenience init(from decoder: Decoder) throws {
        guard let contextUserInfoKey = CodingUserInfoKey.context,
            let managedObjectContext = decoder.userInfo[contextUserInfoKey] as? NSManagedObjectContext,
            let entity = NSEntityDescription.entity(forEntityName: "Feed", in: managedObjectContext) else {  fatalError("Failed to decode Subject!")  }
        self.init(entity: entity, insertInto: managedObjectContext)

        let container = try decoder.container(keyedBy: CodingKeys.self)
        title = try container.decodeIfPresent(String.self, forKey: .title) ?? ""
        albums = try container.decodeIfPresent(Set<Album>.self, forKey: .albums) ?? []
    }
}

回答1:


I want the ordered list of Albums

It is your job to give the Album entity an attribute to sort by. Then, when you fetch, you can pass a sort descriptor to receive the Albums sorted on that attribute.



来源:https://stackoverflow.com/questions/52299902/ordered-list-with-core-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!