TableViewController.swift 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. ////////////////////////////////////////////////////////////////////////////
  2. //
  3. // Copyright 2014 Realm Inc.
  4. //
  5. // Licensed under the Apache License, Version 2.0 (the "License");
  6. // you may not use this file except in compliance with the License.
  7. // You may obtain a copy of the License at
  8. //
  9. // http://www.apache.org/licenses/LICENSE-2.0
  10. //
  11. // Unless required by applicable law or agreed to in writing, software
  12. // distributed under the License is distributed on an "AS IS" BASIS,
  13. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. // See the License for the specific language governing permissions and
  15. // limitations under the License.
  16. //
  17. ////////////////////////////////////////////////////////////////////////////
  18. import UIKit
  19. import RealmSwift
  20. class DemoObject: Object {
  21. @objc dynamic var title = ""
  22. @objc dynamic var date = NSDate()
  23. }
  24. #if !swift(>=4.2)
  25. extension UITableViewCell {
  26. typealias CellStyle = UITableViewCellStyle
  27. typealias EditingStyle = UITableViewCellEditingStyle
  28. }
  29. #endif
  30. class Cell: UITableViewCell {
  31. override init(style: UITableViewCell.CellStyle, reuseIdentifier: String!) {
  32. super.init(style: .subtitle, reuseIdentifier: reuseIdentifier)
  33. }
  34. required init(coder: NSCoder) {
  35. fatalError("NSCoding not supported")
  36. }
  37. }
  38. class TableViewController: UITableViewController {
  39. let realm = try! Realm()
  40. let results = try! Realm().objects(DemoObject.self).sorted(byKeyPath: "date")
  41. var notificationToken: NotificationToken?
  42. override func viewDidLoad() {
  43. super.viewDidLoad()
  44. setupUI()
  45. // Set results notification block
  46. self.notificationToken = results.observe { (changes: RealmCollectionChange) in
  47. switch changes {
  48. case .initial:
  49. // Results are now populated and can be accessed without blocking the UI
  50. self.tableView.reloadData()
  51. case .update(_, let deletions, let insertions, let modifications):
  52. // Query results have changed, so apply them to the TableView
  53. self.tableView.beginUpdates()
  54. self.tableView.insertRows(at: insertions.map { IndexPath(row: $0, section: 0) }, with: .automatic)
  55. self.tableView.deleteRows(at: deletions.map { IndexPath(row: $0, section: 0) }, with: .automatic)
  56. self.tableView.reloadRows(at: modifications.map { IndexPath(row: $0, section: 0) }, with: .automatic)
  57. self.tableView.endUpdates()
  58. case .error(let err):
  59. // An error occurred while opening the Realm file on the background worker thread
  60. fatalError("\(err)")
  61. }
  62. }
  63. }
  64. // UI
  65. func setupUI() {
  66. tableView.register(Cell.self, forCellReuseIdentifier: "cell")
  67. self.title = "TableView"
  68. self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "BG Add", style: .plain,
  69. target: self, action: #selector(backgroundAdd))
  70. self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add,
  71. target: self, action: #selector(add))
  72. }
  73. // Table view data source
  74. override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  75. return results.count
  76. }
  77. override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  78. let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! Cell
  79. let object = results[indexPath.row]
  80. cell.textLabel?.text = object.title
  81. cell.detailTextLabel?.text = object.date.description
  82. return cell
  83. }
  84. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
  85. if editingStyle == .delete {
  86. realm.beginWrite()
  87. realm.delete(results[indexPath.row])
  88. try! realm.commitWrite()
  89. }
  90. }
  91. // Actions
  92. @objc func backgroundAdd() {
  93. // Import many items in a background thread
  94. DispatchQueue.global().async {
  95. // Get new realm and table since we are in a new thread
  96. autoreleasepool {
  97. let realm = try! Realm()
  98. realm.beginWrite()
  99. for _ in 0..<5 {
  100. // Add row via dictionary. Order is ignored.
  101. realm.create(DemoObject.self, value: ["title": TableViewController.randomString(), "date": TableViewController.randomDate()])
  102. }
  103. try! realm.commitWrite()
  104. }
  105. }
  106. }
  107. @objc func add() {
  108. realm.beginWrite()
  109. realm.create(DemoObject.self, value: [TableViewController.randomString(), TableViewController.randomDate()])
  110. try! realm.commitWrite()
  111. }
  112. // Helpers
  113. class func randomString() -> String {
  114. return "Title \(arc4random())"
  115. }
  116. class func randomDate() -> NSDate {
  117. return NSDate(timeIntervalSince1970: TimeInterval(arc4random()))
  118. }
  119. }