Advertisement
Guest User

Untitled

a guest
Jan 20th, 2017
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.17 KB | None | 0 0
  1. import UIKit
  2. import RealmSwift
  3.  
  4. class DemoObject: Object {
  5. dynamic var title = ""
  6. dynamic var date = NSDate()
  7. }
  8.  
  9. class Cell: UITableViewCell {
  10. override init(style: UITableViewCellStyle, reuseIdentifier: String!) {
  11. super.init(style: .subtitle, reuseIdentifier: reuseIdentifier)
  12. }
  13.  
  14. required init(coder: NSCoder) {
  15. fatalError("NSCoding not supported")
  16. }
  17. }
  18.  
  19. class TableViewController: UITableViewController {
  20.  
  21. let realm = try! Realm()
  22. let results = try! Realm().objects(DemoObject.self).sorted(byKeyPath: "date")
  23. var notificationToken: NotificationToken?
  24.  
  25. override func viewDidLoad() {
  26. super.viewDidLoad()
  27.  
  28. setupUI()
  29.  
  30. // Set results notification block
  31. self.notificationToken = results.addNotificationBlock { (changes: RealmCollectionChange) in
  32. switch changes {
  33. case .initial:
  34. // Results are now populated and can be accessed without blocking the UI
  35. self.tableView.reloadData()
  36. break
  37. case .update(_, let deletions, let insertions, let modifications):
  38. // Query results have changed, so apply them to the TableView
  39. self.tableView.beginUpdates()
  40. self.tableView.insertRows(at: insertions.map { IndexPath(row: $0, section: 0) }, with: .automatic)
  41. self.tableView.deleteRows(at: deletions.map { IndexPath(row: $0, section: 0) }, with: .automatic)
  42. self.tableView.reloadRows(at: modifications.map { IndexPath(row: $0, section: 0) }, with: .automatic)
  43. self.tableView.endUpdates()
  44. break
  45. case .error(let err):
  46. // An error occurred while opening the Realm file on the background worker thread
  47. fatalError("\(err)")
  48. break
  49. }
  50. }
  51. }
  52.  
  53. // UI
  54. func setupUI() {
  55. tableView.register(Cell.self, forCellReuseIdentifier: "cell")
  56.  
  57. self.title = "TableView"
  58. self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "BG Add", style: .plain,
  59. target: self, action: #selector(backgroundAdd))
  60. self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add,
  61. target: self, action: #selector(add))
  62. }
  63.  
  64. // Table view data source
  65. override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  66. return results.count
  67. }
  68.  
  69. override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  70. let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! Cell
  71.  
  72. let object = results[indexPath.row]
  73. cell.textLabel?.text = object.title
  74. cell.detailTextLabel?.text = object.date.description
  75.  
  76. return cell
  77. }
  78.  
  79. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
  80. if editingStyle == .delete {
  81. realm.beginWrite()
  82. realm.delete(results[indexPath.row])
  83. try! realm.commitWrite()
  84. }
  85. }
  86.  
  87. // Actions
  88. func backgroundAdd() {
  89. // Import many items in a background thread
  90. DispatchQueue.global().async {
  91. // Get new realm and table since we are in a new thread
  92. let realm = try! Realm()
  93. realm.beginWrite()
  94. for _ in 0..<5 {
  95. // Add row via dictionary. Order is ignored.
  96. realm.create(DemoObject.self, value: ["title": TableViewController.randomString(), "date": TableViewController.randomDate()])
  97. }
  98. try! realm.commitWrite()
  99. }
  100. }
  101.  
  102. func add() {
  103. realm.beginWrite()
  104. realm.create(DemoObject.self, value: [TableViewController.randomString(), TableViewController.randomDate()])
  105. try! realm.commitWrite()
  106. }
  107.  
  108. // Helpers
  109. class func randomString() -> String {
  110. return "Title \(arc4random())"
  111. }
  112.  
  113. class func randomDate() -> NSDate {
  114. return NSDate(timeIntervalSince1970: TimeInterval(arc4random()))
  115. }
  116. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement