我正在使用一个既NSManagedObject
又Codable
的类。这是一个Feed
,它有多个Albums
。我想要Albums
的有序列表,但核心数据迫使我改用 Set,这是没有排序的。我可以使用NSOrderedSet
,但它不适用于Codable
。在核心数据中获取有序列表的最佳方法是什么。下面是我正在尝试制作的模型。
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) ?? []
}
}
我想要专辑的有序列表
您的工作是为相册实体提供要作为排序依据的属性。然后,在获取时,您可以传递排序描述符以接收根据该属性排序的专辑。