我有一个字典,其中包含一个日期的键/值对,其中包含一个按相同日期分组的自定义对象feeds的数组。
用餐对象:
class Meal: NSObject, Codable {
var id: String?
var foodname: String?
var quantity: Float!
var brandName: String?
var quantityType: String?
var calories: Float!
var date: Date?
}
在我的TableView中:
var grouped = Dictionary<Date, [Meal]>()
var listOfAllMeals = [Meal]() //already populated
self.grouped = Dictionary(grouping: self.listOfAllMeals.sorted(by: { ($0.date ?? nilDate) < ($1.date ?? nilDate) }),
by: { calendar.startOfDay(for: $0.date ?? nilDate) })
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return grouped.count
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return Array(grouped.keys)[section] as! String //this throws a thread error
}
这允许用户一天多次上传一顿饭供将来查看,现在我想在一个TableView中显示这些饭,它们按日期分段,并已按最近的日期排序。 我怎么才能做到呢?
在数据模型中,您使用每个条目一天的字典,将键作为数组,并对数组进行排序。
tableview的节数与数组的条目数一样多。 从日期开始创建每个节的标题。 对于每个部分,您从字典中获取餐食数组,因此每个部分具有不同的行数,并且来自eac行的数据从数组的一行中获取。
例如,为了获取第3节第5行的数据,您从索引3处的日期数组中获取日期,您在字典中查找日期并获得餐食数组,索引5处的餐食提供数据。
为区段创建结构
struct Section {
let date : Date
let meals : [Meal]
}
并将分组字典映射到section
的数组
var sections = [Section]()
let sortedDates = self.grouped.keys.sorted(>)
sections = sortedDates.map{Section(date: $0, meals: self.grouped[$0]!)}
您可以添加日期格式化程序,以更有意义地显示date
实例。
注意:
考虑使用较少的选项和结构,而不是NSObject
子类。 与nscoding
codable
不同,nsobjectprotocot
不要求符合nsobjectprotocot
。 并且永远不要将属性声明为隐式未包装可选。