iOS Swift 汇总 CoreData 属性值

iOS Swift Summing up CoreData attribute values

Setup: Xcode version: 7.1 Beta, 
Firmware: iOS 9, 

我正在尝试从 Core Data 访问一个值以获得购买产品的总计。我已经检查了一个问题,但它在 Obj C 中。CoreData 详细信息:

实体:购物车

属性:fName(字符串)、fCost(整数 16)、fQuantity(整数 16)

获取代码如下:

let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let managedContext : NSManagedObjectContext = appDelegate.managedObjectContext!
let fetchRequest = NSFetchRequest(entityName: "Cart")
fetchRequest.returnsObjectsAsFaults = false
do {
    let results = try managedContext.executeFetchRequest(fetchRequest)
    print("===\(results)")

} catch let error as NSError {
    print(error)
}

打印(结果)输出如下:

[<Tif.Cart: 0x7f8d19e60d00> (entity: Cart; id: 0xd000000000240000 <x-coredata://5D617B2C-35BC-43B4-BEC1-40AABA96C558/Cart/p9> ; data: {
    fCost = 30;
    fName = "Milk";
    fQuantity = 2;
}), <Tif.Cart: 0x7f8d19e7cd80> (entity: Cart; id: 0xd000000000280000 <x-coredata://5D617B2C-35BC-43B4-BEC1-40AABA96C558/Cart/p10> ; data: {
    fCost = 60;
    fName = "Butter";
    fQuantity = 1;
})]

我正在使用table查看单元格来显示核心数据并执行总计。

var cart = [NSManagedObject]()
let order = cart[indexPath.row]
cell.fNLabel.text = order.valueForKey("fName")! as? String
cell.fCLabel.text = "Rs \(order.valueForKey("fCost") as! NSNumber)"
cell.fQLabel.text = "\(order.valueForKey("fQuantity") as! NSNumber)"
let fQ = order.valueForKey("fQuantity") as! Int
let fC = order.valueForKey("fCost") as! Int
let total = fQ * fC
totalArray.append(total)
grandTotal = totalArray.sum() // sum() is an extension that calculates the sum of integer values
print(grandTotal)
grandTotalLabel.text = "\(grandTotal)"
cell.fTLabel.text = "Rs \(total)"

我得到了 grandTotal,但每次我拉 table 时,该值都会添加到最后一个值中。

我还阅读了有关使用 NSFetchRequestController 选项的信息,但我根本无法使用它。

您似乎在用 tableView:cellForRowAtIndexPath: 方法计算总计。这绝对不是这样做的正确位置,因为它只会计算 可见单元格 .

的总计
let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let managedContext : NSManagedObjectContext = appDelegate.managedObjectContext!
let fetchRequest = NSFetchRequest(entityName: "Cart")
fetchRequest.returnsObjectsAsFaults = false
do {
    let results = try managedContext.executeFetchRequest(fetchRequest)
    print("===\(results)")

    // Calculate the grand total...
    var grandTotal = 0
    for order in results {
        let fQ = order.valueForKey("fQuantity") as! Int
        let fC = order.valueForKey("fCost") as! Int
        grandTotal += fC * fQ
    }
    print("Grand total = \(grandTotal)")

} catch let error as NSError {
    print(error)
}