简体   繁体   English

快速排序自定义对象的NSMutableArray

[英]Sort NSMutableArray of custom objects in swift

i tried to sort array of custom objects. 我试图对自定义对象数组进行排序。 when an array contains one object, it returns the sorted Array with an object. 当一个数组包含一个对象时,它将返回一个带有对象的排序数组。 But if an array contains multiple object, it crashed 但是,如果数组包含多个对象,则会崩溃

class Plans:NSObject{
   var price:Int

   var name:String?
   .. 
   ..
   .. 
}


func price(array:NSMutableArray,sortKey:NSString)->Int{
        var sortDescriptor:NSSortDescriptor = NSSortDescriptor(key: sortKey, ascending: true)
        var sortedArray:NSArray = array.sortedArrayUsingDescriptors([sortDescriptor])//Crashes
        var apt:Plans = sortedArray.objectAtIndex(0) as Plans
        return apt.price
}

function call: 函数调用:

self.price(array,sortKey:"price") //array contains array of Plans objects

Crash: 崩溃:

*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<pjct.Plans 0x7fb8a7bb7af0> valueForUndefinedKey:]: this class is not key value coding-compliant for the key price.'

First make Plans class implements is Comparable and Equatable . 首先使Plans课程实施的工具具有ComparableEquatable Here is how: 方法如下:

extension Plans: Comparable {}
extension Plans: Equatable {}

Then implement two function: 然后实现两个功能:

func ==(lhs: Plans, rhs: Plans) -> Bool {
    return lhs.price == rhs.price
}

func <(lhs: Plans, rhs: Plans) -> Bool {
    return lhs.price < rhs.price
}

Now you can use standard operators to sort your array. 现在,您可以使用标准运算符对数组进行排序。 Here is how 这是怎么

let sortedArray = (objcArray as AnyObject as [Plans]).sorted(<)

Or if you don't want to implement this protocols you can simply sort array like this: 或者,如果您不想实现此协议,则可以对数组进行如下排序:

let sortedArray = (objcArray as AnyObject as [Plans]).sorted {$0.price < $1.price}

Ok. 好。 Finally i was able to figure out the issue. 最终,我能够找出问题所在。 I can't sort array that contains Int value. 我无法对包含Int值的数组进行排序。 so i changed "price" from Int to NSNumber 所以我将“价格”从Int更改为NSNumber

var price:Int

to

var price:NSNumber

now it works. 现在可以了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM