Как мне сохранить структуру данных в Realm?
Хочу сохранить структуру данных в реалм и отображать эти данные из реалма в tableView
class ViewController: UIViewController {
class Record : Comparable {
let calendar: Calendar = {
var calendar = Calendar.autoupdatingCurrent
calendar.locale = Locale(identifier: "ru_RU")
return calendar
}()
var date: Date
init(date: Date) {
self.date = date
}
static func == (lhs: Record, rhs: Record) -> Bool {
lhs.date == rhs.date
}
static func < (lhs: Record, rhs: Record) -> Bool {
lhs.date < rhs.date
}
}
class Section : Record {
private let formatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy/MM"
formatter.locale = Locale(identifier: "ru_RU")
return formatter
}()
var title: String {
formatter.string(from: date)
}
var items = [SectionItem]()
func addRecord(_ record: SectionItem) {
items.append(record)
}
}
class SectionItem : Record {
private let formatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy/MM/dd HH:mm"
formatter.locale = Locale(identifier: "ru_RU")
return formatter
}()
var year: Int {
calendar.component(.year, from: date)
}
var month: Int {
calendar.component(.month, from: date)
}
var title: String {
formatter.string(from: date)
}
}
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var datePicker: UIDatePicker!
@IBOutlet weak var createButton: UIButton!
var items = [SectionItem]()
var sections = [Section]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
self.tableView.register(UINib(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: "TableViewCell")
}
func sortData() {
if items.isEmpty {
return
}
items.sort()
sections = []
var year = 0
var month = 0
var section: Section!
for item in items {
if section == nil || item.year != year || item.month != month {
section = Section(date: item.date)
sections.append(section)
}
section.addRecord(item)
year = item.year
month = item.month
}
}
@IBAction func createButtonAction(_ sender: Any) {
let dateRecord = SectionItem(date: datePicker.date)
items.append(dateRecord)
sortData()
tableView.reloadData()
}
}
extension ViewController: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sections[section].title
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sections[section].items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell") as! TableViewCell
cell.labelCell?.text = sections[indexPath.section].items[indexPath.row].title
return cell
}