我正在处理核心数据以存储不同的活动,并跟踪每项活动的执行次数。该实体称为“活动”,其属性为“name”和“total”。当一项活动多次执行时,我想更改该特定活动的属性“总计”(通过添加+1),而不是添加新活动。我怎样才能做到这一点?到目前为止,这是我的代码:
let appDel = (UIApplication.sharedApplication().delegate as! AppDelegate)
let context: NSManagedObjectContext = appDel.managedObjectContext
let request = NSFetchRequest(entityName: "Activities")
request.returnsObjectsAsFaults = false
request.predicate = NSPredicate(format:"(name == %@)", name)
do {
let results = try context.executeFetchRequest(request) as! [Activities]
if results.count == 0 {
newActivity.setValue(1, forKey: "total")
newActivity.setValue(name), forKey: "name")
do {
try context.save()
}
catch {
print(error)
}
}
}
catch let error as NSError {
print(error)
}
}
答案 0 :(得分:0)
如果您想要更新(如果我没有记错的话),您可以像这样更改total
:
results.total = YourWantedNumber or results.setValue(YourWantedNumber, forKey: "total")
context.save()