Diego Aguirre Diego Aguirre - 6 months ago 19
iOS Question

In iOS does realm support deleting a row in a tableview with animation?

For example this is the following code I have regarding deleting a tableview row.

// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the row from the data source
self.array = [Note allObjects];
RLMRealm *realm = RLMRealm.defaultRealm;
[realm beginWriteTransaction];
NSLog(@"%@",self.array[indexPath.row]);
[realm deleteObject:self.array[indexPath.row]];
[realm commitWriteTransaction];
}
}


Although I get the initial result I want of deleting the row it unfortunately has no animation so the abrupt update of the tableview just doesn't look good. I understand that normally this is the actual method to use achieve the animation in a tableview
[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];


By the way this is the closest thing I found regarding my question but it just doesn't work for me. https://github.com/realm/realm-cocoa/issues/1045

Any ideas?

Answer

You are on the right track.

Do you update your UI somewhere with a notification block? ->

// Observe Realm Notifications
self.token = [realm addNotificationBlock:^(NSString *note, RLMRealm * realm) {
  [myViewController updateUI];
}];

If yes, then you first have to animate the deletion and then remove the object from realm:

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
  if (editingStyle == UITableViewCellEditingStyleDelete) {
      [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
      [self deleteItemAtIndexPath: indexPath];
  }
}

- (void)deleteItemAtIndexPath:(NSIndexPath *)indexPath {
  // Delete the row from the data source
  self.array = [Note allObjects];
  RLMRealm *realm = RLMRealm.defaultRealm;
  [realm beginWriteTransaction];
  NSLog(@"%@",self.array[indexPath.row]);
  [realm deleteObject:self.array[indexPath.row]];
  [realm commitWriteTransaction];
}

Anyway. Just animate your row first and then delete the data from your Array/Realm :)

Comments