Замена атрибута в CoreData
У меня есть сущность в CoreDate под названием BudgetDetail. У меня есть приведенный ниже код, который я хочу обновить атрибут "остальное", однако, похоже, что добавление новой записи, а не обновление.
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)")
}
}
}
Похоже, что новая запись добавлена, а не обновляется в цикле. Я не уверен, почему это происходит, и любая помощь будет оценена.
1 ответ
Решение
Эти строки:
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)
создать новый управляемый объект и установить значения его атрибутов. Если вы просто хотите обновить существующий объект, удалите эти строки и замените на:
i.setValue(newRemaining, forKey: budgetRemaningKeyToUpdate)