gpt4 book ai didi

ios - 如何在 NSMutableArray 中对对象进行分组并在 Objective-C 中划分为单独的 NSMutableArray

转载 作者:行者123 更新时间:2023-11-28 23:54:30 27 4
gpt4 key购买 nike

我有这样的 NSMutableArray:

// NSMutableArray *Data = (NSMUtableArray(NSDictionary))
Data = {"Device": "A1", "Temperature": "25", "datetime": "2013.02.03"},
{"Device": "A2", "Temperature": "25", "datetime": "2013.02.03"},
{"Device": "A3", "Temperature": "25", "datetime": "2013.02.03"},
{"Device": "A1", "Temperature": "25", "datetime": "2013.02.04"},
{"Device": "A2", "Temperature": "25", "datetime": "2013.02.04"}.

如何按照“日期时间”将其分解并分组到单独的 NSMutableArray 中。如上情况将分为:

Data_d1 = {"Device": "A1", "Temperature": "25", "datetime": "2013.02.03"},
{"Device": "A2", "Temperature": "25", "datetime": "2013.02.03"},
{"Device": "A3", "Temperature": "25", "datetime": "2013.02.03"}

Data_d2 = {"Device": "A1", "Temperature": "25", "datetime": "2013.02.04"},
{"Device": "A2", "Temperature": "25", "datetime": "2013.02.04"}

最佳答案

您可以使用以下代码来实现:

let data:[[String: String]] = [
["Device": "A1",
"Temperature": "25",
"datetime": "2013.02.03"],

["Device": "A2",
"Temperature": "25",
"datetime": "2013.02.03"],

["Device": "A3",
"Temperature": "25",
"datetime": "2013.02.03"],

["Device": "A1",
"Temperature": "25",
"datetime": "2013.02.04"],

["Device": "A2",
"Temperature": "25",
"datetime": "2013.02.04"]]

let dateTimeArray = data.compactMap({ $0["datetime"] })
let uniqueDateTimeArray = Array(Set(dateTimeArray))

var desiredSeparatedArray = [[[String: String]]]()
for dateTime in uniqueDateTimeArray {
var arrayForDateTime = [[String: String]]()
for element in data {
if element["datetime"] == dateTime {
arrayForItem.append(element)
}
}
desiredSeparatedArray.append(arrayForDateTime)
}

最终的desiredSeparatedArray就是答案!!

关于ios - 如何在 NSMutableArray 中对对象进行分组并在 Objective-C 中划分为单独的 NSMutableArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51515965/

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