如何在Coredata&#xff1f中积累托管对象字符串属性的长度;
这是Coredata中的项目实体,项目包含一个属性标题(类型为字符串?):
let item = Item(context: moc)
item.title = "hello world"
我想计算所有项目的总和。Title.Count.Count:
let item_0 = Item(context: moc)
item_0.title = "a" // title.count is 1
let item_1 = Item(context: moc)
item_1.title = "ab" // title.count is 2
let item_2 = Item(context: moc)
item_2.title = "abc" // title.count is 3
// sum Item.title.count is 1 + 2 + 3 = 6
我不想遍历所有项目对象,我想要要使用以下内容:
let req = NSFetchRequest<NSFetchRequestResult>(entityName: "Item")
req.resultType = .dictionaryResultType
let countDesc = NSExpressionDescription()
countDesc.name = "titlesCount"
countDesc.expressionResultType = .integer64AttributeType
countDesc.expression = NSExpression(forFunction: "sum:", arguments: [NSExpression(forKeyPath: "title.count")])
req.propertiesToFetch = [countDesc]
let results = try moc.fetch(req) as! [NSDictionary] // Crash!!!
let dict = results.first!
let count = dict["titlesCount"] as! Int64
不幸的是,以下代码崩溃如下:
***终止由于未知的例外“ nsinvalidargumentException”,原因是:'无效键盘(在属性名称之后继续):title'
是否有办法使用nsexpression来sum.title.title.count.count.count?我不想迭代所有项目。
多谢! )
Here is a Item entity In CoreData, and Item contains a property title(type is String?):
let item = Item(context: moc)
item.title = "hello world"
I want to calculate the sum of all Item.title.count:
let item_0 = Item(context: moc)
item_0.title = "a" // title.count is 1
let item_1 = Item(context: moc)
item_1.title = "ab" // title.count is 2
let item_2 = Item(context: moc)
item_2.title = "abc" // title.count is 3
// sum Item.title.count is 1 + 2 + 3 = 6
I don't want to looping through all Item objects,I would like to use something like the following:
let req = NSFetchRequest<NSFetchRequestResult>(entityName: "Item")
req.resultType = .dictionaryResultType
let countDesc = NSExpressionDescription()
countDesc.name = "titlesCount"
countDesc.expressionResultType = .integer64AttributeType
countDesc.expression = NSExpression(forFunction: "sum:", arguments: [NSExpression(forKeyPath: "title.count")])
req.propertiesToFetch = [countDesc]
let results = try moc.fetch(req) as! [NSDictionary] // Crash!!!
let dict = results.first!
let count = dict["titlesCount"] as! Int64
Unfortunately, the above code crashes as follows:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid keypath (continues after attribute name): title'
Is there a way to use NSExpression to sum Item.title.count? I don't want to iterate over all Items.
Thanks a lot! ;)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如何获得每个项目的长度然后将它们求和?
我希望它有帮助! :)
how about obtaining the length of each Item and then summing them up?
I hope it helps! :)