gpt4 book ai didi

swift - 如何对 NSUserDefault 中的 NSMutableDictionary 存储数组进行排序?

转载 作者:行者123 更新时间:2023-11-28 10:16:35 27 4
gpt4 key购买 nike

我有一个用 NSUserDefault 保存的 NSMutableDictionary 数组,我想根据每个 NSMutableDictionary 中的“时间戳”键(值是一个字符串)对数组进行排序:我用来检索数组的代码:

     if let chatsArray = NSUserDefaults().arrayForKey("myChatsList") as? [NSMutableDictionary]{
print(chatsArray)
//sort the array
print(sortedArray)
}

这就是我的数组的样子:

[{
eventBadge = 1;
eventId = "-KWE39B6Dh7rDzaF-xy4";
lastMessage = uyfgduihgvifudhviufhvdf;
timestamp = 20;
unreadMessage = 2;
}, {
eventBadge = 1;
eventId = "-KWWc99ex8f7ksq8TR2U";
lastMessage = uyfgduihgvifudhviufhvdf;
timestamp = 5;
unreadMessage = 1;
}, {
eventBadge = 1;
eventId = "-KWE5OYRZnZ5-p3LUotL";
lastMessage = uyfgduihgvifudhviufhvdf;
timestamp = 10;
unreadMessage = 2;
}]

我尝试使用 NSSDescriptor :

var descriptor: NSSortDescriptor = NSSortDescriptor(key: "timestamp", ascending: true)
chatsArray.sortedArrayUsingDescriptors([descriptor])

还可以使用类型化数组(在使用新类之后)

mutableChatsArray.sortInPlace{ ($0.compare($1.timestamp) == NSComparisonResult.OrderedDescending)}

到目前为止还没有成功...感谢您的帮助

最佳答案

Swift 3 示例

  let chatsArray = [[
"eventBadge" : 1,
"eventId" : "-KWE39B6Dh7rDzaF-xy4",
"lastMessage" : "uyfgduihgvifudhviufhvdf",
"timestamp" : 20,
"unreadMessage" : 2,
], [
"eventBadge" : 1,
"eventId" : "-KWWc99ex8f7ksq8TR2U",
"lastMessage" : "uyfgduihgvifudhviufhvdf",
"timestamp" : 5,
"unreadMessage" : 1,
], [
"eventBadge" : 1,
"eventId" : "-KWE5OYRZnZ5-p3LUotL",
"lastMessage" : "uyfgduihgvifudhviufhvdf",
"timestamp" : 10,
"unreadMessage" : 2,
]] as [[String:Any]]

// to get the timestamp value and store it inside an array with order
let arrayTimeStamp = (chatsArray.flatMap{$0["timestamp"]} as! Array<Int>).sorted(by: >)
print(arrayTimeStamp) // [20, 10, 5]

//to order an array of dictionaries

let TimeStamp = chatsArray.sorted{$0["timestamp"] as! Int > $1["timestamp"] as! Int }

print(TimeStamp)

//[["eventId": "-KWE39B6Dh7rDzaF-xy4", "lastMessage":"uyfgduihgvifudhviufhvdf", "timestamp": 20, "unreadMessage": 2, "eventBadge": 1],
//["eventId": "-KWE5OYRZnZ5-p3LUotL", "lastMessage": "uyfgduihgvifudhviufhvdf", "timestamp": 10, "unreadMessage": 2, "eventBadge": 1],
//["eventId": "-KWWc99ex8f7ksq8TR2U", "lastMessage": "uyfgduihgvifudhviufhvdf", "timestamp": 5, "unreadMessage": 1, "eventBadge": 1]]

关于swift - 如何对 NSUserDefault 中的 NSMutableDictionary 存储数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40590895/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com