Search code examples
iosobjective-cdelegatesnsnotificationcenter

iOS: Should I use a delegate or an NSNotification in this situation?


I have a database that updates with new data constantly. I use this data as my datasource for my UITableView. Currently, I am using NSNotifications to alert my UITableView to insert, delete or update new data. However, I've been thinking it would be much better to use delegates because it is one on one.

Here is some code to better demonstrate what is going on.

- (void)insertObject:(NSNotification *)notification {
    NSNumber *object = [notification object];

    [self.tableView beginUpdates];
    [self.data insertObject:object atIndex:0];
    [self.tableView insertRowsAtIndexes:[NSIndexSet indexSetWithIndex:0] withAnimation:NSTableViewAnimationEffectNone];
    [self.tableView endUpdates];
 }

Solution

  • In a larger scope, database updates are typically an event that many parts of your project could be interested in. This is why Core Data itself uses notifications, rather than a delegate approach. Yes, you could go either way, but I would tend to follow Apple's lead on this pattern. (maddy's comment to your post does have an excellent explanation btw)