Website Links

Monday 14 December 2015

Swift - Sorting NSManagedObjects (from Core Data)

Class to represent Core Data Table

You will need to add a class to represent your core data table:

  // My core data object only had the field name
  // it also had relationships but I didn't need to access 
  // these so they are excluded. 
  import CoreData

  @objc(Mode)
  class Mode: NSManagedObject {
    @NSManaged var name: String
  }

Following that you will need to ensure your core data table references the class or you'll get an error, you can do this in the same place you would add columns to the table:



Performing the sort

First you must load the data, ensure that you save it as an array of your object representation of the Core Data table.

  ...

  let modes : [Mode] = try context.executeFetchRequest(request)
    as! [Mode]

  // We must specify whether we want to sort in
  // ascending or descending order
  // $0 represents the first item, $1 represents the second
  // their fields can be access as normal 
  appState.modes = modes.sort({$0.name.compare($1.name) 
    == NSComparisonResult.OrderedAscending}) as [Mode]

  ...

No comments:

Post a Comment