gpt4 book ai didi

ios - 解析 Core Data 中按提取请求分组的 NSDictionary 结果

转载 作者:行者123 更新时间:2023-11-28 10:13:29 25 4
gpt4 key购买 nike

我需要使用 CoreData 从表中获取一些统计信息。我用过this使用“group by”表达式提取数据的手册。

这是我的源代码:

var popularGuestNames: [String] = []
let keypathExp = NSExpression(forKeyPath: "guestName")
let expression = NSExpression(forFunction: "count:", arguments: [keypathExp])

let countDesc = NSExpressionDescription()
countDesc.expression = expression
countDesc.name = "count"
countDesc.expressionResultType = .integer64AttributeType

let request = NSFetchRequest<NSFetchRequestResult>(entityName: "GuestsTable")
request.returnsObjectsAsFaults = false
request.propertiesToGroupBy = ["guestName"]
request.propertiesToFetch = ["guestName", countDesc]
request.resultType = .dictionaryResultType

let matchedGuests = try? context.fetch(request)
guard matchedGuests != nil else {return popularGuestNames}

但结果是我得到了 [Any] 类型的 matchedGuests。我被困在这里。我可以使用 print 看到有 JSON 对象:

Optional(
[{
count = 1;
guestName = "\U0412\U0430\U043d\U044f";
}, {
count = 13;
guestName = "\U0413\U043e\U0441\U0442\U044c 1";
}, {
count = 9;
guestName = "\U0413\U043e\U0441\U0442\U044c 2";
}, {
count = 3;
guestName = "\U0413\U043e\U0441\U0442\U044c 3";
}, {
count = 1;
guestName = "\U0413\U043e\U0441\U0442\U044c 4";
}, {
count = 1;
guestName = "\U0413\U043e\U0441\U0442\U044c 5";
}, {
count = 1;
guestName = "\U041d\U043d\U043d";
}, {
count = 1;
guestName = "\U0422\U0435\U0441\U0442";
}, {
count = 1;
guestName = "\U0422\U0435\U0441\U0442 \U0442\U0435\U0441\U0442\U043e\U0432\U0438\U0447";
}, {
count = 1;
guestName = "\U0423\U0410\U0443\U043f\U0430\U0438\U0443\U0430\U0433\U0443";
}])

但是我找不到解析它的方法。我知道我应该使用 JSONSerialization.jsonObject,但此方法需要数据类型的输入变量。而且我不明白如何将 Any 转换为 Data。

最佳答案

首先,核心数据获取的结果绝对不是 JSON 对象

其次要更具体!

由于获取请求的返回类型显然是字典,因此使用泛型类型传递 NSDictionary

let request = NSFetchRequest<NSDictionary>(entityName: "GuestsTable")

然后将类型相应地转换为实际类型[[String:Any]]

var matchedGuests = [[String:Any]]()
...
if let result = try? context.fetch(request) as! [[String:Any]] {
matchedGuests = result
}

即使发生 try? 错误,假定提取请求有效,强制展开的返回类型也永远不会导致崩溃。


如果你只想要客人名字映射数组

let popularGuestNames = matchedGuests.flatMap { $0["guestName"] as? String }

关于ios - 解析 Core Data 中按提取请求分组的 NSDictionary 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44725869/

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