我在一个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个男人”怎么办?我希望这样的标题位于结果数组的开头。目前这类记录介于两者之间。

最佳答案

我建议将CoreData结果转换为一个book对象数组(我认为您最终还是会这样做),实现一个自定义的sorter函数。类似于下面的函数:

static func sortByTitle(books: [Book]) -> [Book]{
    return books.sorted(by: sorterForTitlesAlphaNumeric)
}

SorterPortleteSalphanumeric的实现如下所示:
//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
}

10-08 04:05