ios - How to create alphabetical section headers with NSFetchedResultsController - Swift 3 -


i using nsfetchedresultscontroller populate tableview. tableview can quite long because shows list of people, , want sort alphabetically. know need use titleforheaderinsection, stuck on how first letter of each object in fetchedobjectscontroller.fetchedobjects , display section header sort it, how contacts app works.

this view controller looks like.

var fetchedresultscontroller: nsfetchedresultscontroller<client> = {     let fetchrequest: nsfetchrequest<client> = client.fetchrequest()     let sortdescriptors = [nssortdescriptor(key: "name", ascending: false)]     fetchrequest.sortdescriptors = sortdescriptors     return nsfetchedresultscontroller(fetchrequest: fetchrequest, managedobjectcontext: coredatastack.context, sectionnamekeypath: "name", cachename: nil) }()  override func numberofsections(in tableview: uitableview) -> int {     guard let sections = fetchedresultscontroller.sections else { return 0 }     return sections.count }   override func tableview(_ tableview: uitableview, numberofrowsinsection section: int) -> int {     guard let sections = fetchedresultscontroller.sections else { return 0 }     return sections[section].numberofobjects }   override func tableview(_ tableview: uitableview, cellforrowat indexpath: indexpath) -> uitableviewcell {     let cell = tableview.dequeuereusablecell(withidentifier: "clientcell", for: indexpath)     let client = fetchedresultscontroller.object(at: indexpath)     cell.textlabel?.text = client.name      return cell }  override func tableview(_ tableview: uitableview, commit editingstyle: uitableviewcelleditingstyle, forrowat indexpath: indexpath) {     if editingstyle == .delete {         let client = fetchedresultscontroller.object(at: indexpath)         clientcontroller.sharedcontroller.delete(client)     } } 

this small example of how can headers texts, use class test have name, applying map using characters.prefix first characters of names , after casting string , sorting have need

var arrayofusers : [user] = [user(name:"test"),user(name:"pest"),user(name:"aest"),user(name:"nest"),user(name:"best")] let finalarray = arrayofusers.map({string.init($0.name.characters.prefix(1)) }).sorted(by: {$0 < $1}) debugprint(finalarray) 

console log result

["a", "b", "n", "p", "t"]

hope helps you


Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -