NSSortDescriptor in swift 3

N

To sort an json array using NSSortDescriptor in swift3

 

NSSortDescriptor :

A sort descriptor describes a comparison used to sort a collection of objects. You create an instance of NSSortDescriptor that specifies the property key to be sorted, and whether the comparison should be in ascending, or descending order. A sort descriptor can also specify a method to use when comparing the property key values, rather than the default of compare:.

It is important to remember that NSSortDescriptor does not sort objects. It provides the description of how to sort objects. The actual sorting is done by other classes, often NSArray or NSMutableArray.

NSSortDescriptor objects are constructed with the following parameters:

  • key: for a given collection, the key for the corresponding value to be sorted on for each object in the collection.
  • ascending: a boolean specifying whether the collection should be sorted in ascending (YES) or descending (NO) order.

 

// replace the urlname

let task = URLSession.shared.dataTask(with: NSURL(string: “urlname”)! as URL, completionHandler: { (data, response, error) -> Void in

       if (data != nil || error == nil)

                {

                let dict: AnyObject? = try! JSONSerialization.jsonObject(with: data!, options: []) as AnyObject?

                 if (dict is NSArray)

                {

                    let dictArray : NSArray = dict as! NSArray

                    let aArray : NSMutableArray = NSMutableArray(array: dictArray)

                     //replace keyname whatever you want an array should be sort ,for example , json array contain “id” key 

                     //you want array should be sort using that “id” , keyname should be “id”

                   // if you want array ascending then set value  “true” for key ascending, otherwise set to “false”

                    let descriptor: NSSortDescriptor = NSSortDescriptor(key: “keyname”, ascending: true)

                    // sortedResult is an result array which is sorted using key defined in NSSortDescriptor

                     sortedResults = aArray.sortedArray(using: [descriptor]) as NSArray

                   print(sortedResults)

                    }

                   }

        })

        task.resume()

About the author

Pragati Rode
By Pragati Rode

Category