【发布时间】:2018-01-23 16:22:45
【问题描述】:
我有一个应用程序,它将我的 NSManagedObject 值“totalGold”增加 5,保存它,并在每次使用表视图的滑动删除功能时从 CoreData 中删除表视图单元格。 我的 NSManagedObject 子类是:
extension Goal {
@nonobjc public class func fetchRequest() -> NSFetchRequest<Goal> {
return NSFetchRequest<Goal>(entityName: "Goal");
}
@NSManaged public var created: NSDate?
@NSManaged public var desc: String?
@NSManaged public var title: String?
@NSManaged public var difficulty: String?
@NSManaged public var totalGold: Int64
@NSManaged public var frequency: String?
}
滑动删除代码为:
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == UITableViewCellEditingStyle.delete{
let fetchRequest: NSFetchRequest<Goal> = Goal.fetchRequest()
do {
let array_users = try context.fetch(fetchRequest)
let user = array_users[0]
var count: Int64 = user.totalGold
count += 5
user.totalGold = count
print(user.value(forKey: "totalGold")!)
let str = String(describing: user.totalGold)
totalGold.text = str
ad.saveContext()
}
catch {
print("Error with request: \(error)")
}
let managedObject: NSManagedObject = controller.object(at: indexPath) as NSManagedObject;
context.delete(managedObject)
ad.saveContext()
}
}
然后,当我想重新加载totalGold 的最新值时,在viewDidLoad 中,我调用attemptFetch2 函数来检索“totalGold”的最新值并将其设置为UILabel 的文本,就像在滑动删除中所做的那样:
func attemptFetch2(){
let fetchRequest: NSFetchRequest<Goal> = Goal.fetchRequest()
do {
let array_users = try context.fetch(fetchRequest)
let user = array_users[0]
print(user.value(forKey: "totalGold")!)
let str = String(describing: user.value(forKey: "totalGold") as! Int64)
totalGold.text = str
//save the context
do {
try context.save()
print("saved!")
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
} catch {
}
}
catch {
print("Error with request: \(error)")
}
}
此代码工作正常,可以正确保存对象并正确获取它,除非 tableview 为空。当 tableview 为空时(或者更好的说法:当我删除最后一个 table view 单元格时),我的“totalGold”NSManagedObject 值被重置为其默认值 0。所以基本上,除非至少有一个 table view 单元格,否则这段代码才有效始终在我的表格视图中,这使得“totalGold”似乎只保存在我给定的表格视图中。每次删除最后一个表格视图单元格时,我有什么办法不重置“totalGold”?
【问题讨论】: