【问题标题】:Sorting NSMutableArray depending on priority根据优先级对 NSMutableArray 进行排序
【发布时间】:2016-02-02 11:52:26
【问题描述】:

我有一个 NSMutableArray 的字典。

dic1 = ["user":"Smith","points":12,"lastPoints":4,online:3MonthsAgo(NSDate)]
dic2 = ["user":"Mike","points":22,"lastPoints":3,online:2MonthsAgo(NSDate)]
dic3 = ["user":"Mark","points":22,"lastRank":5,online:now(NSDate)]
dic4 = ["user":"Jay","points":16,"lastPoints":2,online:2minutes(NSDate)]
dic5 = ["user":"Alex","points":13,"lastPoints":5,online:1hr(NSDate)]
dic6 = ["user":"Peter","points":22,"lastPoints":3,online:2days(NSDate)]

我想通过 3 种方式重新整理, 最先获得最高分的用户将首先显示 所以

Mike:22
Mark:22
Peter:22
Jay:16
Alex:13
Smith:12

现在我确实使用了

let sort = NSSortDescriptor(key: "points", ascending: false)

接下来我要根据 lastPoints 示例再次对这些用户进行排序

Mark:22:5
Mike:22:3
Peter:22:3
Jay:16:2
Alex:13:5
Smith:12:4

然后根据最后在线日期对 Mike 和 Peter 在数组中的位置进行排序。 现在当我尝试

 let sortAgain = NSSortDescriptor(key: "lastPoints", ascending: false) and then
let sortAgain2 = NSSortDescriptor(key: "online", ascending: false)

它会删除我之前所做的那种 points,并根据 lastPoints 再次对所有内容进行排序。 我希望它根据点对它们进行排序,然后查看点是否相等,根据 lastPoints 对这些点数据进行排序。如果 lastPoints 相等,则根据“在线”日期对这些相等的数据进行排序。

【问题讨论】:

  • 你告诉我们你想要什么。但是您忘记告诉我们您尝试了什么以及遇到了什么问题。
  • 我坚持根据 lastPoints 和 Online 日期对它们进行排序,因为当我尝试时,它会对它们进行排序,但 Mark:22 不在顶部,

标签: swift nsmutablearray nsdictionary nssortdescriptor


【解决方案1】:

试试这个:

let result = arr.sort {
    let p0 = $0["points"] as! Int
    let p1 = $1["points"] as! Int

    let lp0 = $0["lastPoints"] as! Int
    let lp1 = $1["lastPoints"] as! Int

    let online0 = $0["online"] as! NSDate
    let online1 = $1["online"] as! NSDate

    if p0 != p1 {
        return p0 > p1
    } else if lp0 != lp1 {
        return lp0 > lp1
    } else {
        return online0.timeIntervalSince1970 > online1.timeIntervalSince1970
    }
}

【讨论】:

  • 我的眼睛,这么多强制转换 :) 请注意,强制转换(在 Swift 中通常是强制的东西)会在您最意想不到的时候导致应用程序崩溃。
  • @Code 不一样 android 有没有类似的功能?
【解决方案2】:

我建议使用sort(或sortInPlace)函数,您可以在其中指定自定义排序块。例如,如果您将所有Dictionaries 放入Array,您可以执行以下操作:

array.sort { (dict1, dict2) -> Bool in
    if let p1 = dictionary1["points"] as? Int, let p2 = dictionary2["points"] as? Int {
        if let l1 = dictionary1["lastPoints"] as? Int, let l2 = dictionary2["lastPoints"] as? Int where p1 == p2 {
            return l1 > l2
        }
        return p1 > p2
    }
    return false
}

你必须自己做出一个合适的实现,但这个概念应该适合你。

【讨论】:

  • 所以我必须将所有对象与每个人进行比较,然后从中得到一个新数组?
  • 您不必为每一对运行它。 sort 函数会为您执行此操作,您只需指定块,在我的示例中,dict1dict2 是排序过程中给定点的数组中的两个给定项。 sort 函数返回一个已排序的新数组。 sortInPlace 将用排序的数组替换数组。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-05
  • 1970-01-01
  • 2011-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多