带核心数据的有序列表 [英] Ordered List With Core Data
问题描述
我正在使用同时是 NSManagedObject
和 Codable
的类。这是 Feed
,并且有多个相册
。我想要相册
的有序列表,但是Core Data迫使我改用Set,但没有排序。我可以使用 NSOrderedSet
,但是在 Codable
上不能很好地工作。在Core Data中获取有序列表的最佳方法是什么。下面是我要工作的模型。
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) ?? []
}
}
推荐答案
我想要相册的有序列表
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.
这篇关于带核心数据的有序列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!