如何通过对象的多个属性对自定义对象列表进行排序

时间:2015-03-30 07:17:06

标签: ios swift ios8 nsdate

有人可以帮助我按多个参数对自定义对象列表进行排序 我想按date1和date2对它进行排序,并可选择b所有三个属性,但无论我尝试它失败:(
我的目标:

class MyObject : NSManagedObject{
   @NSManaged var date1:NSDate
   @NSManaged var date2:NSDate
   @NSManaged var key:Int
}

这是我尝试排序这些对象的列表失败:

var sortedArray1 = sorted(unorderedList, { (o1: MyObject, o2: MyObject) -> Bool in{
            return o1.date1 == o2.date1 ? (o1.date2 < o2.date2) : (o1.date1 < o2.date1)
        }

        var sortedArray2 = sorted(unorderedList, { (o1: MyObject, o2: MyObject) -> Bool in
            return (o1.date1.compare(o2.date1) == NSComparisonResult.OrderedAscending) == (o1.date1.compare(o2.date1) == NSComparisonResult.OrderedAscending) ? (o1.date2.compare(o2.date2) == NSComparisonResult.OrderedAscending) : (o1.date1.compare(o2.date1) == NSComparisonResult.OrderedAscending))
        });

1 个答案:

答案 0 :(得分:1)

尝试一下,让我知道:

unorderedList.sorted({
    if $0.date1 < $1.date1 {
        return true
    } else if $0.date1 == $date2 {
        return $0.date2 < $1.date2
    }
    return false
})

public func == (left: NSDate, right: NSDate) -> Bool {
    return left.isEqualToDate(right)
}

public func != (left: NSDate, right: NSDate) -> Bool {
    return !left.isEqualToDate(right)
}

public func > (left: NSDate, right: NSDate) -> Bool {
    return left.compare(right) == NSComparisonResult.OrderedDescending
}

public func < (left: NSDate, right: NSDate) -> Bool {
    return left.compare(right) == NSComparisonResult.OrderedAscending
}