An immutable description of how to order a collection of objects based on a property common to all the objects.


You construct an instance of NSSortDescriptor by specifying the key path of the property to be compared, the order of the sort (ascending or descending), and (optionally) a selector to use to perform the comparison. The three-argument constructor allows you to specify other comparison selectors such as caseInsensitiveCompare(_:) and localizedCompare(_:). Sorting raises an exception if the objects to be sorted do not respond to the sort descriptor’s comparison selector.

There are a number of situations in which you can use sort descriptors, for example:

  • To sort an array (an instance of NSArray or NSMutableArray—see sortedArray(using:) and sort(using:))

  • To directly compare two objects (see compare(_:to:))

  • To specify how the elements in a table view should be arranged (see sortDescriptors)

  • To specify how the elements managed by an array controller should be arranged (see sortDescriptors)

  • If you are using Core Data, to specify the ordering of objects returned from a fetch request (see sortDescriptors)


Initializing a Sort Descriptor

init(key: String?, ascending: Bool)

Returns an NSSortDescriptor object initialized with a given property key path and sort order, and with the default comparison selector.

init(key: String?, ascending: Bool, selector: Selector?)

Returns an NSSortDescriptor object initialized with a given property key path, sort order, and comparison selector.

init(key: String?, ascending: Bool, comparator: Comparator)

Returns an NSSortDescriptor object initialized to do with the given ordering and comparator block.

Getting Information About a Sort Descriptor

var ascending: Bool

A Boolean value that indicates whether the receiver specifies sorting in ascending order.

var key: String?

The receiver’s property key path.

var selector: Selector?

The selector the receiver specifies to use when comparing objects.

Using Sort Descriptors

func compare(Any, to: Any)

Returns an NSComparisonResult value that indicates the ordering of two given objects.

var reversedSortDescriptor: Any

A sort descriptor with the sort order reversed.

func allowEvaluation()

Force a sort descriptor that was securely decoded to allow evaluation.

Create an NSComparator for the Sort Descriptor.

var comparator: Comparator

An NSComparator for the sort descriptor.

Instance Properties


Inherits From

See Also


enum ComparisonResult

Constants that indicate sort order.