简体   繁体   中英

iOS Swift Summing up CoreData attribute values

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

I am trying to access a value from Core Data to get the gross total of product purchased. I have checked a question on the same, but it is in Obj C. CoreData details:

Entity: Cart

Attributes: fName (String), fCost (Integer 16), fQuantity (Integer 16)

Retrieving code is as below:

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)
}

Print(results) output is as below:

[<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;
})]

I am using tableView cell to display the core data and performing the total.

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)"

I get the grandTotal, but every time I pull the table the value gets added to the last value.

I also read about using NSFetchRequestController option, but I wasn't able to work with it at all.

It looks like you're calculating the grand total in the tableView:cellForRowAtIndexPath: method. This is most definitely not the correct place to do so as it will only calculate the grand total for visible cells .

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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM