iOS Swift总结CoreData属性值

时间:2015-10-08 07:36:43

标签: ios swift uitableview core-data xcode7.1beta

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

我正在尝试访问Core Data中的值以获取所购买产品的总数。我已经检查了一个相同的问题,但它是在Obj C. CoreData详细信息:

实体:购物车

属性:fName(String),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;
})]

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

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,但每次拉表时,值都会被添加到最后一个值。

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

1 个答案:

答案 0 :(得分:1)

看起来您正在使用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)
}