TableViewController.swift 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  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. break
  52. case .update(_, let deletions, let insertions, let modifications):
  53. // Query results have changed, so apply them to the TableView
  54. self.tableView.beginUpdates()
  55. self.tableView.insertRows(at: insertions.map { IndexPath(row: $0, section: 0) }, with: .automatic)
  56. self.tableView.deleteRows(at: deletions.map { IndexPath(row: $0, section: 0) }, with: .automatic)
  57. self.tableView.reloadRows(at: modifications.map { IndexPath(row: $0, section: 0) }, with: .automatic)
  58. self.tableView.endUpdates()
  59. break
  60. case .error(let err):
  61. // An error occurred while opening the Realm file on the background worker thread
  62. fatalError("\(err)")
  63. break
  64. }
  65. }
  66. }
  67. // UI
  68. func setupUI() {
  69. tableView.register(Cell.self, forCellReuseIdentifier: "cell")
  70. self.title = "TableView"
  71. self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "BG Add", style: .plain,
  72. target: self, action: #selector(backgroundAdd))
  73. self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add,
  74. target: self, action: #selector(add))
  75. }
  76. // Table view data source
  77. override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  78. return results.count
  79. }
  80. override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  81. let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! Cell
  82. let object = results[indexPath.row]
  83. cell.textLabel?.text = object.title
  84. cell.detailTextLabel?.text = object.date.description
  85. return cell
  86. }
  87. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
  88. if editingStyle == .delete {
  89. realm.beginWrite()
  90. realm.delete(results[indexPath.row])
  91. try! realm.commitWrite()
  92. }
  93. }
  94. // Actions
  95. @objc func backgroundAdd() {
  96. // Import many items in a background thread
  97. DispatchQueue.global().async {
  98. // Get new realm and table since we are in a new thread
  99. autoreleasepool {
  100. let realm = try! Realm()
  101. realm.beginWrite()
  102. for _ in 0..<5 {
  103. // Add row via dictionary. Order is ignored.
  104. realm.create(DemoObject.self, value: ["title": TableViewController.randomString(), "date": TableViewController.randomDate()])
  105. }
  106. try! realm.commitWrite()
  107. }
  108. }
  109. }
  110. @objc func add() {
  111. realm.beginWrite()
  112. realm.create(DemoObject.self, value: [TableViewController.randomString(), TableViewController.randomDate()])
  113. try! realm.commitWrite()
  114. }
  115. // Helpers
  116. class func randomString() -> String {
  117. return "Title \(arc4random())"
  118. }
  119. class func randomDate() -> NSDate {
  120. return NSDate(timeIntervalSince1970: TimeInterval(arc4random()))
  121. }
  122. }