user4363124
user4363124

Reputation: 121

How can I sort a UITableView using CoreData information in swift?

I'm new to core data and I'm trying to sort my UITableView from data fetched from CoreData. I know how to do this using an array, but I'm struggling to find out how to do it with CoreData. I've read similar questions but it's either in Objective-c -which I haven't learned- or it's not solving my specific problem. My CoreData entity is named numbers and it stores numbers of type Float that the user passes in. My code here is in my viewDidAppear method, the first line is my declaration of myNumbers array which is globally available in that class. ***Take note that my entity has more than one attribute, I have an attribute "number" and an attribute "name" which is a string.

    var myNumbers: Array<AnyObject> = []

override func viewDidAppear(animated: Bool) {

    let appDeleg: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
    let context: NSManagedObjectContext = appDeleg.managedObjectContext!
    let fetchreq = NSFetchRequest(entityName: "Numbers")

    //Would I be adding the sort descriptor here?
    let sortDescriptor = NSSortDescriptor(key: "numbersAttribute", ascending: true)
    fetchreq.sortDescriptors = [sortDescriptors]

    myNumbers = context.executeFetchRequest(fetchreq, error: nil)!
    tableView.reloadData()

}

Now this is the code in my cellForRowAtIndexPath method:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let CellID: NSString = "myCell"

    var cell: CustomCell = tableView.dequeueReusableCellWithIdentifier(CellID) as CustomCell

    if let indexpth = indexPath as NSIndexPath! {

        var data: NSManagedObject = myNumbers[indexpth.row] as NSManagedObject
        cell.theTextLabel?.text = data.valueForKeyPath("tName") as? String

        cell.theDetailTextLabel?.text = data.valueForKeyPath("tNumber") as? String

    }

I want to order the data in my table view based on the "tNumber" attribute in the Numbers entity.

Upvotes: 0

Views: 2793

Answers (1)

timgcarlson
timgcarlson

Reputation: 3146

You can do this using an NSSortDescriptor. Do the following before doing the fetch request to populate myNumbers.

// Note that the key is the attribute of your Numbers entity that you are sorting
let sortDescriptor = NSSortDescriptor(key: "tNumber", ascending: true)
fetchreq.sortDescriptors = [sortDescriptors]

This should work, but the best way to accomplish loading data from Core Data into a table is to use a NSFetchedResultsController. This is especially true if you're dealing with a very large or transient data set.

Upvotes: 3

Related Questions