ioscore-datansmanagedobjectnsentitydescription

replacing attribute within CoreData


I have an entity within CoreDate called BudgetDetail. I have the below code which i want to update the attribute 'remaining' however it seems to be adding a new record rather than updating.

func checksBudgetDetail(budgetName: String, spendAmount: Double, date: NSDate){
        print("budget name = \(budgetName)")

        //fetch results fron income entity and place in array
        let budgetDetailResults: [AnyObject] = try! context.executeFetchRequest(budgetDetail)
     print("budget results loaded")

        //if there are no incomes saved, do nothing.
        if budgetDetailResults.isEmpty {
        }

        //if there are incomes saved, retrieve name and amount
        else {
            for i in budgetDetailResults {
                print("in loop")

                 let name = (i.valueForKey(budgetNameKeyToUpdate)! as! String)
                let amount = Double(i.valueForKey(budgetAmountKeyToUpdate)!.stringValue)
                let durationType = (i.valueForKey(budgetDurationTypeKeyToUpdate)! as! String)
                let durationOccurance = Double(i.valueForKey(budgetDurationOccuranceKeyToUpdate)!.stringValue)
                let remaining = (i.valueForKey(budgetRemaningKeyToUpdate)!.stringValue)
                let startDate = (i.valueForKey(startDateKeyToUpdate)! as! NSDate)
                let endDate = (i.valueForKey(endDateKeyToUpdate)! as! NSDate)

                if name == budgetName {
                    print("just logged a spend against the budget \(name)")

                    //if the date in the on the spend is within the startDate and endDate, call the updateBudgetDetailEntity to update the remaining budget
                    if startDate.compare(date) == .OrderedAscending && endDate.compare(date) == .OrderedDescending {

                        print("the spend which has just been logged is also within the dates of \(name)'s budget")

                        let newRemaining : Double

                        print("\(budgetName) has a old reamining amount of:\(remaining)")

                        newRemaining = Double(remaining)! - spendAmount

                        print("\(budgetName) has a new reamining amount of:\(newRemaining)")

                        let entity = NSEntityDescription.entityForName("BudgetDetail", inManagedObjectContext: context)!
                        let saveBudgetEntity = NSManagedObject(entity: entity, insertIntoManagedObjectContext:context)

                        // add user input to the relevant entity
                        saveBudgetEntity.setValue(name, forKey: budgetNameKeyToUpdate)
                        saveBudgetEntity.setValue(amount, forKey: budgetAmountKeyToUpdate)
                        saveBudgetEntity.setValue(durationType, forKey: budgetDurationTypeKeyToUpdate)
                        saveBudgetEntity.setValue(durationOccurance, forKey: budgetDurationOccuranceKeyToUpdate)
                        saveBudgetEntity.setValue(startDate, forKey: startDateKeyToUpdate)
                        saveBudgetEntity.setValue(endDate, forKey: endDateKeyToUpdate)
                        saveBudgetEntity.setValue(newRemaining, forKey: budgetRemaningKeyToUpdate)


                    do {
                        try context.save()
                        print("new remaining attriute saved")
                    } catch _ {
                        print("new remaining attriute didnt saved")
                    }


                    }
                    else {
                        //would need to create a new record with new start and end dates
                    }
                }
                else {

                }

               print("\(date)")
                print("Name:\(budgetName), startDate:\(startDate), endDate:\(endDate)")
            }
        }

}

It looks as if a new record is been added rather than updating the one within the loop. I am unsure why this is happening and any help would be appreciated.


Solution

  • These lines:

    let entity = NSEntityDescription.entityForName("BudgetDetail", inManagedObjectContext: context)!
    let saveBudgetEntity = NSManagedObject(entity: entity, insertIntoManagedObjectContext:context)
    // add user input to the relevant entity
    saveBudgetEntity.setValue(name, forKey: budgetNameKeyToUpdate)
    saveBudgetEntity.setValue(amount, forKey: budgetAmountKeyToUpdate)
    saveBudgetEntity.setValue(durationType, forKey: budgetDurationTypeKeyToUpdate)
    saveBudgetEntity.setValue(durationOccurance, forKey: budgetDurationOccuranceKeyToUpdate)
    saveBudgetEntity.setValue(startDate, forKey: startDateKeyToUpdate)
    saveBudgetEntity.setValue(endDate, forKey: endDateKeyToUpdate)
    saveBudgetEntity.setValue(newRemaining, forKey: budgetRemaningKeyToUpdate)
    

    create a new managed object and set its attribute values. If you just want to update the existing object, delete those lines and replace with:

    i.setValue(newRemaining, forKey: budgetRemaningKeyToUpdate)