gpt4 book ai didi

ios - 如果从 CoreData 中删除最后一个 UITableViewCell,则 NSManagedObject 值将重置

转载 作者:行者123 更新时间:2023-11-30 12:13:42 25 4
gpt4 key购买 nike

我有一个应用程序,它将我的 NSManagedObject 值“totalGold”增加 5,保存它,并在每次使用 TableView 的滑动删除功能时从 CoreData 中删除 TableView 单元格。我的 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 为空时(或者更好的说法:当我删除最后一个 TableView 单元格时),我的“totalGold”NSManagedObject 值将重置为其默认值 0。因此,本质上,此代码仅在至少有一个 TableView 单元格时才有效始终在我的 TableView 中,这使得“totalGold”看起来好像只保存在我给定的 TableView 中。有什么办法让我在每次删除最后一个 TableView 单元格时不重置“totalGold”?

最佳答案

您的模型设置错误。属性totalGold是一个与任何个人目标无关的全局属性。所以它不应该是 goal 对象的属性。它应该存储在单独的 user 实体中,或者完全存储在不同的存储中(例如 userDefaults)。

关于ios - 如果从 CoreData 中删除最后一个 UITableViewCell,则 NSManagedObject 值将重置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45698070/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com