TableViewController.m 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  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 "TableViewController.h"
  19. #import <Realm/Realm.h>
  20. // Realm model object
  21. @interface DemoObject : RLMObject
  22. @property NSString *title;
  23. @property NSDate *date;
  24. @end
  25. @implementation DemoObject
  26. // None needed
  27. @end
  28. static NSString * const kCellID = @"cell";
  29. static NSString * const kTableName = @"table";
  30. @interface TableViewController ()
  31. @property (nonatomic, strong) RLMResults *array;
  32. @property (nonatomic, strong) RLMNotificationToken *notification;
  33. @end
  34. @implementation TableViewController
  35. #pragma mark - View Lifecycle
  36. - (void)viewDidLoad
  37. {
  38. [super viewDidLoad];
  39. self.array = [[DemoObject allObjects] sortedResultsUsingKeyPath:@"date" ascending:YES];
  40. [self setupUI];
  41. // Set realm notification block
  42. __weak typeof(self) weakSelf = self;
  43. self.notification = [self.array addNotificationBlock:^(RLMResults *data, RLMCollectionChange *changes, NSError *error) {
  44. if (error) {
  45. NSLog(@"Failed to open Realm on background worker: %@", error);
  46. return;
  47. }
  48. UITableView *tv = weakSelf.tableView;
  49. // Initial run of the query will pass nil for the change information
  50. if (!changes) {
  51. [tv reloadData];
  52. return;
  53. }
  54. // changes is non-nil, so we just need to update the tableview
  55. [tv beginUpdates];
  56. [tv deleteRowsAtIndexPaths:[changes deletionsInSection:0] withRowAnimation:UITableViewRowAnimationAutomatic];
  57. [tv insertRowsAtIndexPaths:[changes insertionsInSection:0] withRowAnimation:UITableViewRowAnimationAutomatic];
  58. [tv reloadRowsAtIndexPaths:[changes modificationsInSection:0] withRowAnimation:UITableViewRowAnimationAutomatic];
  59. [tv endUpdates];
  60. }];
  61. }
  62. #pragma mark - UI
  63. - (void)setupUI
  64. {
  65. self.title = @"TableViewExample";
  66. self.navigationItem.leftBarButtonItem =
  67. [[UIBarButtonItem alloc] initWithTitle:@"BG Add"
  68. style:UIBarButtonItemStylePlain
  69. target:self
  70. action:@selector(backgroundAdd)];
  71. self.navigationItem.rightBarButtonItem =
  72. [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
  73. target:self
  74. action:@selector(add)];
  75. }
  76. #pragma mark - UITableViewDataSource
  77. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  78. {
  79. return self.array.count;
  80. }
  81. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  82. {
  83. UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellID];
  84. if (!cell) {
  85. cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
  86. reuseIdentifier:kCellID];
  87. }
  88. DemoObject *object = self.array[indexPath.row];
  89. cell.textLabel.text = object.title;
  90. cell.detailTextLabel.text = object.date.description;
  91. return cell;
  92. }
  93. - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
  94. forRowAtIndexPath:(NSIndexPath *)indexPath
  95. {
  96. if (editingStyle == UITableViewCellEditingStyleDelete) {
  97. RLMRealm *realm = RLMRealm.defaultRealm;
  98. [realm beginWriteTransaction];
  99. [realm deleteObject:self.array[indexPath.row]];
  100. [realm commitWriteTransaction];
  101. }
  102. }
  103. #pragma mark - Actions
  104. - (void)backgroundAdd
  105. {
  106. dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
  107. // Import many items in a background thread
  108. dispatch_async(queue, ^{
  109. // Get new realm and table since we are in a new thread
  110. @autoreleasepool {
  111. RLMRealm *realm = [RLMRealm defaultRealm];
  112. [realm beginWriteTransaction];
  113. for (NSInteger index = 0; index < 5; index++) {
  114. // Add row via dictionary. Order is ignored.
  115. [DemoObject createInRealm:realm withValue:@{@"title": [self randomString],
  116. @"date": [self randomDate]}];
  117. }
  118. [realm commitWriteTransaction];
  119. }
  120. });
  121. }
  122. - (void)add
  123. {
  124. RLMRealm *realm = RLMRealm.defaultRealm;
  125. [realm beginWriteTransaction];
  126. [DemoObject createInRealm:realm withValue:@[[self randomString], [self randomDate]]];
  127. [realm commitWriteTransaction];
  128. }
  129. #pragma - Helpers
  130. - (NSString *)randomString
  131. {
  132. return [NSString stringWithFormat:@"Title %d", arc4random()];
  133. }
  134. - (NSDate *)randomDate
  135. {
  136. return [NSDate dateWithTimeIntervalSince1970:arc4random()];
  137. }
  138. @end