martin
martin

Reputation: 1974

Swift - Sorting core data in sections

I've managed to sort the data received from my core data alphabetically, and now I want put the usernames in sections for each letter. I understand that the easiest way to do this is by using NSFetchedResultsController, but I can't figure out how to use this (very few tutorials covering Swift).

So my code looks like this:

override func viewDidAppear(animated: Bool) {

    let appDel:AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
    let context:NSManagedObjectContext = appDel.managedObjectContext!
    let freq = NSFetchRequest(entityName: "Message")
    let en = NSEntityDescription.entityForName("Message", inManagedObjectContext: context)

    let fetchRequest = NSFetchRequest(entityName: "Message")
    let sortDescriptor = NSSortDescriptor(key: "username", ascending: true)
    fetchRequest.sortDescriptors = [sortDescriptor]

    myList = context.executeFetchRequest(fetchRequest, error: nil) as [Model]

    tv.reloadData()    
}

func numberOfSectionsInTableView(tableView: UITableView) -> Int {

    return 1
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{

    return myList.count
}

I was hoping someone could shed some light over the NSFetchedResultsController and help me get on my way.

If I'm not completely wrong, the initialization looks something like this, although I can't figure out the "cache name":

let resultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: myList, sectionNameKeyPath: "username", cacheName: <#String?#>)

Any suggestions on how to proceed would be appreciated.

Upvotes: 0

Views: 1212

Answers (1)

Mundi
Mundi

Reputation: 80265

You can set up the fetched results controller easily by copying and tweaking the code from the Xcode template. (Create a new project, Master-Detail, check "Use Core Data", copy from MasterViewController.)

The following is not the ideal solution, but I think it is appropriate for your level of experience. When you add the username attribute to the Message entity object, also add another attribute with the first letter. Then use the name of this new attribute as the sectionNameKeyPath parameter when creating the fetched results controller.

Don't worry too much about the cache parameter. You can just put any string there, such as "Root", or even pass nil to not use cache which is also fine in most use cases.

Upvotes: 1

Related Questions