我在我的一个iOS项目中使用过coredata。我有一个名为“Books”的表(列:title,author,status,publishdate),我需要以升序模式的列标题对它们进行排序的方式获取记录。这就是我为完成它而写的:
let fetchRequest = NSFetchRequest<NSFetchRequestResult>.init(entityName: "Books")
let sort = NSSortDescriptor(key: "title", ascending: true)
fetchRequest.sortDescriptors = [sort]
do {
let result = try coreViewContext.fetch(fetchRequest)
} catch let err as NSError {
print(err.debugDescription)
}
如果我的书有“100个故事,20个电影,300个男人”这样的书?我希望这些标题位于结果数组的开头。目前这些记录介于两者之间。
答案 0 :(得分:1)
我建议将CoreData结果转换为一个图书对象数组(我假设你最终还是这样做),实现自定义排序功能。类似下面的功能:
static func sortByTitle(books: [Book]) -> [Book]{
return books.sorted(by: sorterForTitlesAlphaNumeric)
}
sorterForTitlesAlphaNumeric的实现看起来像这样:
//Compare this book's title to that book's title
static func sorterForTitlesAlphaNumeric(this : Book, that: Book) -> Bool {
return this.title < that.title
}
与试图使用预先烘烤的NSSortDescriptor
相比,这将使您获得更精细的控制。这样,如果您以后在路上决定根据标题进行过滤,然后发布日期,您可以将上述功能更改为
//Compare this book's title to that book's title
static func sorterForTitlesAlphaNumeric(this : Book, that: Book) -> Bool {
if this.title == that.title {
return this.publishDate < that.publishDate
}
return this.title < that.title
}