簡體   English   中英

如何在CoreData中累積托管對象String屬性的長度?

[英]How to accumulate length of managed object String property in CoreData?

這是CoreData中的一個Item實體,Item包含一個屬性title(類型是String?):

let item = Item(context: moc)
item.title = "hello world"

我想計算所有 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

我不想循環遍歷所有 Item 對象,我想使用如下內容:

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”而終止應用程序,原因:“無效的密鑰路徑(在屬性名稱后繼續):標題”

有沒有辦法使用 NSExpression 對 Item.title.count 求和? 我不想遍歷所有項目。

非常感謝! ;)

如何獲得每個項目的長度然后總結它們?

let req = NSFetchRequest<NSFetchRequestResult>(entityName: "Item")
req.resultType = .dictionaryResultType
        
let countDesc = NSExpressionDescription()
countDesc.name = "titlesCount"
countDesc.expressionResultType = .integer64AttributeType
countDesc.expression = NSExpression(forFunction: "length:", arguments: [NSExpression(forKeyPath: "name")])
            
req.propertiesToFetch = [countDesc]

do {
    let results = try moc.fetch(req) as! [NSDictionary]
    return results.reduce(0) { $0 + ($1["titlesCount"] as! Int) } // this sums up all the individual item lengths
} catch {
    print("Error fetching data from context \(error)")
}

我希望它有幫助! :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM