带核心数据的有序列表

时间:2018-09-12 16:38:52

标签: ios swift core-data codable

我正在同时使用NSManagedObjectCodable的类。这是Feed,并且有多个Albums。我想要Albums的有序列表,但是Core Data迫使我改用Set,但它不是有序列的。我可以使用NSOrderedSet,但不能与Codable配合使用。在Core Data中获取有序列表的最佳方法是什么。以下是我要制作的模型。

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 个答案:

答案 0 :(得分:1)

  

我想要相册的有序列表

赋予相册实体一个属性以为您的工作。然后,在获取数据时,您可以传递排序描述符,以接收对该属性排序的相册。