gpt4 book ai didi

ios - 当 UITableView 为空时无法获取 CoreData 属性值

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

我有一个应用程序,每次使用滑动删除 tableviewcell 功能时,都会将金额 5 添加到我的核心数据属性值中。核心数据配置如下所示:/image/16YR6.png commit editStyle 类中的代码如下所示:

    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.value(forKey: "totalGold") as! Int64
count += 5
user.setValue(count, forKey: "totalGold")
let str = String(describing: user.value(forKey: "totalGold") as! Int64)
totalGold.text = str
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)")
}
let managedObject: NSManagedObject = controller.object(at: indexPath) as NSManagedObject;
context.delete(managedObject)
ad.saveContext()
}
}

然后我在 viewDidLoad 中使用相同的获取过程,如下所示:

let fetchRequest: NSFetchRequest<Goal> = Goal.fetchRequest()
do {

let array_users = try context.fetch(fetchRequest)

let user = array_users[0]
let count: Int64 = user.value(forKey: "totalGold") as! Int64
user.setValue(count, 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 单元格。然后,当我尝试在没有单元格的情况下重新加载 View 时,在尝试在线获取时出现索引超出范围错误:

 let user = array_users[0]

显然,这是因为当我尝试获取totalGold的最新值时,它找不到它并且它认为没有值,所以我获取错误了。如何正确获取totalGold的最新属性值?

最佳答案

你可以把它们放在条件中

let fetchRequest: NSFetchRequest<Goal> = Goal.fetchRequest()
do {
let array_users = try context.fetch(fetchRequest)
if array_users.count > 0 {
let user = array_users[0]
let count: Int64 = user.value(forKey: "totalGold") as! Int64
user.setValue(count, 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)")
}

关于ios - 当 UITableView 为空时无法获取 CoreData 属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45684806/

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