I have implemented the FetchedControllerDelegate, and I have the table view sorted so that everything is displayed alphabetically, and the section headers are working. However, for a section with letter "T", for example, the tableview has two different sections if the name of the place isn't the exact same word. For example, for "Taco Bell" and "Texas", they are each under a different section with the label "T". I want it so that every word that starts with a "T" is under the "T" section name. I've found information on how to do this but it has been for Obj-C instead of Swift. Also, there's been answers involving setting a transient property but I don't know where to start to implement that
How to use the first character as a section name
NSFetchedResultsController with sections created by first letter of a string
// Add Sort Descriptors
let sortDescriptor = NSSortDescriptor(key: "name", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor]
// Initialize Fetched Results Controller
let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest,
managedObjectContext: self.managedObjectContext,
sectionNameKeyPath: "name", cacheName: nil)
Then the table view methods:
override func tableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int {
return fetchedResultsController.sectionForSectionIndexTitle(title, atIndex: index)
}
override func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? {
return fetchedResultsController.sectionIndexTitles
}
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 20
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if let sections = fetchedResultsController.sections {
let currentSection = sections[section]
if let char = currentSection.name.characters.first {
return String(char)
}
return currentSection.name
}
return nil
}
Add a computed property in your NSManagedObject
subclass and return name's first character there like,
var nameFirstChar: String {
get {
if let char = self.name?.characters.first {
return String(char)
}
return "#"
}
}
Now set nameFirstChar as your section keypath like,
let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext, sectionNameKeyPath: "nameFirstChar", cacheName: nil)