在swift中对自定义对象的NSMutableArray进行排序

时间:2014-10-30 10:08:25

标签: ios swift ios8 nsmutablearray nssortdescriptor

我试图对自定义对象进行排序。当数组包含一个对象时,它返回带有对象的已排序数组。但是如果一个数组包含多个对象,它就会崩溃

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
}

函数调用:

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

崩溃:

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

2 个答案:

答案 0 :(得分:3)

首先使Plans类实现为ComparableEquatable。方法如下:

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

然后实现两个功能:

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

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

现在您可以使用标准运算符对数组进行排序。这是如何

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

或者,如果您不想实现此协议,您可以简单地对数组进行排序:

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

答案 1 :(得分:2)

确定。最后我能够找出问题所在。我不能排序包含Int值的数组。所以我将“价格”从Int更改为NSNumber

var price:Int

var price:NSNumber

现在可行。