ios - Swift 3.1 Coredata Sorting Alphabetically Ascending but Keep Records Starting with Numbers in the Beginning -
i have used coredata in 1 of ios projects. have table named "books" (columns: title, author, status, publishdate) , need fetch records in way ordered column title in ascending mode. have written accomplish it:
let fetchrequest = nsfetchrequest<nsfetchrequestresult>.init(entityname: "books") let sort = nssortdescriptor(key: "title", ascending: true) fetchrequest.sortdescriptors = [sort] { let result = try coreviewcontext.fetch(fetchrequest) } catch let err nserror { print(err.debugdescription) } what if have books titles "100 stories, 20 movies, 300 men"? want such titles @ beginning of result array. such records lie in between.
i recommend converting coredata result array of book objects (which assume anyway) implementing custom sorter function. function below:
static func sortbytitle(books: [book]) -> [book]{ return books.sorted(by: sorterfortitlesalphanumeric) } the implementation sorterfortitlesalphanumeric this:
//compare book's title book's title static func sorterfortitlesalphanumeric(this : book, that: book) -> bool { return this.title < that.title } that give finer grain control trying use pre-baked nssortdescriptor. way if later down road decide filter based on title , publish date can change above function
//compare book's title 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 }
Comments
Post a Comment