【问题标题】:How to combine attributes in Core Data using Swift?如何使用 Swift 在 Core Data 中组合属性?
【发布时间】:2020-06-03 01:14:46
【问题描述】:

我有一个基本应用程序,允许用户从一系列动物中进行选择:[Cat, Bird, Dog] 并记录他们在一天中看到它的次数。我正在使用 Core Data 来保存每个用户的会话。当我从 Core Data 获取结果时,它们看起来像:

动物:鸟,见过:2

动物:猫,见过:1

动物:鸟,见过:4

Sessions 是实体,而属性是 animal: String 和 seen: Int。

然后我为每只动物贴上一个标签,上面写着总看到的次数。 示例:鸟 - 总数:6,猫 - 总数:1,狗 - 总数 0

如何将每个动物属性的“已见”属性加在一起以生成每个动物属性的总数量?下面的代码生成提取的核心数据结果。

 let context = coreDataStack.managedContext
 let fetchRequest = NSFetchRequest<Sessions>(entityName: "Sessions")

   do {
                let tasks = try context.fetch(fetchRequest)

                   for task in tasks {
                    print("Animal: \(task.animal)")
                    print("Seen: \(String(describing: seen))")
                   }
               } catch let error {
                   print("Error: \(error.localizedDescription)")
               }

【问题讨论】:

  • 请出示Sessions的声明。基本上我们需要知道task 是什么。

标签: swift core-data


【解决方案1】:

根据你的问题,我猜每个数据条目都会有:

  1. 动物名称(字符串)
  2. 已见计数 (Int)

所以,也许您可​​以尝试使用字典来保存每只动物的总数

var animalCount = [String : Int]()

for task in tasks {
    if animalCount[task.animal] == nil {
        animalCount[task.animal] = task.seen
            //I assume this seen is a property of this task
    } else {
        animalCount[task.animal] = animalCount[task.animal]! + task.seen
    }
}
animalCount.forEach{print("Animal: \($0.key) - Total: \($0.value)")}

【讨论】:

  • 已解决。谢谢!是的,动物名称是 String 类型, seen 是 Int 类型。
猜你喜欢
  • 2015-02-20
  • 1970-01-01
  • 2016-08-14
  • 1970-01-01
  • 2011-11-13
  • 2019-02-05
  • 2017-11-11
相关资源
最近更新 更多