我有一个带有值的表格视图。数据库是由核心数据组成的。您可以将值设置为 true 或 false。我只想将这些值与 true 相加。为了总结这些值,我有这个代码。
func printData() {
//Shorthand Argument Names
//let request: NSFetchRequest<Gegenstand> = Gegenstand.fetchRequest()
//let records = try! context.fetch(request) as [NSManagedObject]
let sum = ViewController.liste.reduce(0) { $0 + ($1.value(forKey: "gewicht") as? Double ?? 0) }
print("Gesamtgewicht: \(sum) kg")
gewicht = sum
if gewicht > 3500 {
gewichtLabel.textColor = .red
gewichtLabel.text = "\(gewicht) kg"
}
}
我用 if 函数尝试过,但我不知道如何将它与核心数据一起使用。
如果需要,您可以在 Core Data 中完成所有操作。使用
true
过滤 NSPredicate
,并让 Core Data 使用 NSExpression
计算总和。
首先设置获取请求以仅获取属性为
true
的条目,并确保它返回字典类型的结果(我不知道你的布尔值叫什么,所以这里我称之为 flag
。将您的房产名称放在那里):
let fetchRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "Gegenstand")
fetchRequest.resultType = .dictionaryResultType
fetchRequest.predicate = NSPredicate(format: "flag = true")
然后设置一个
NSExpressionDescription
,可以得到gewicht
值的总和:
let sumExpression = NSExpression(format: "sum:(gewicht)")
let sumExpressionDescription = NSExpressionDescription()
sumExpressionDescription.expression = sumExpression
sumExpressionDescription.resultType = .double
sumExpressionDescription.name = "gewichtSum"
它的作用是创建一种新的属性,Core Data 可以理解该属性,其中值是
gewicht
值的总和,并命名为 gewichtSum
。获取请求知道如何使用这种属性。你这样做:
fetchRequest.propertiesToFetch = [ sumExpressionDescription ]
由于 fetch 使用
dictionaryResultType
,因此运行 fetch 将返回一个字典数组。它是一个数组,因为 fetch
始终返回一个数组,但这里只有一个条目。该数组条目中的字典有一个名为 gewichtSum
的键,用于根据上面的表达式计算出的 Double
属性。你得到这样的值:
do {
let result = try context.fetch(fetchRequest)
if result.count > 0,
let sumInfo = result[0] as? [String:Double],
let gewichtSum: Double = sumInfo["gewichtSum"] {
print("Sum: \(gewichtSum)")
}
} catch {
...
}
上面的
print
语句打印所有 gewicht
值的总和,其中 flag
为 true。由于 flag
,它仅包含 NSPredicate
的真实值,并且由于表达式描述,它包含总和。
这就是我现在的解决方案。我希望这就像练习一样。期待您的评论。
//Gewicht summieren
func printData() {
//Shorthand Argument Names
let request: NSFetchRequest<Gegenstand> = Gegenstand.fetchRequest()
request.returnsObjectsAsFaults = false
request.predicate = NSPredicate(format: "eingepackt = true")
do {
let gesamtListe = try context.fetch(request)
let sum = gesamtListe.reduce(0) { $0 + ($1.value(forKey: "gewicht") as? Double ?? 0) }
print("Gesamtgewicht: \(sum) kg")
//gewicht = sum
if sum > 3500 {
gewichtLabel.textColor = .red
gewichtLabel.text = "\(sum) kg"
} else {
gewichtLabel.textColor = .black
gewichtLabel.text = "\(sum) kg"
}
} catch {
print("Gesamtgewicht konnte nicht berechnet werden.")
}
}
创建一个 isValue=true 的 coreData fetchRequest,
计算返回fetchRequest的总和
func fetchAllWithTrue() -> [Gegenstand] {
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: Gegenstand)
fetchRequest.predicate = NSPredicate(format: “isValue== YES")
do {
let fetchedObjects = try coreDataManager.context.fetch(fetchRequest) as? [Gegenstand]
return fetchedObjects
} catch {
print(error.localizedDescription)
return [Gegenstand]()
}
}