SNRFetchedResultsController
is a "port" (not exactly) ofNSFetchedResultsController
from iOS to OS X. It is not a drop in replacement forNSFetchedResultsController
, but performs many of the same tasks in relation to managing results from a Core Data fetch and notifying a delegate when objects are inserted, deleted, updated, or moved in order to update the UI.
As someone who is primarily an iOS guy, having this class around makes the thought of doing some larger Mac OS X and AppKit-based stuff much more inviting.
Implementing it is this easy:
NSFetchRequest *request = [[NSFetchRequest alloc] init];
request.entity = [NSEntityDescription entityForName:@"Car" inManagedObjectContext:context];
request.sortDescriptors = [NSArray arrayWithObjects:[NSSortDescriptor sortDescriptorWithKey:@"year" ascending:YES], nil];
request.predicate = [NSPredicate predicateWithFormat:@"wheels.@count != 0"];
request.fetchBatchSize = 20;
self.fetchedResultsController = [[SNRFetchedResultsController alloc] initWithManagedObjectContext:context fetchRequest:request];
self.fetchedResultsController.delegate = self;
NSError *error = nil;
[self.fetchedResultsController performFetch:&error];
if (error) {
NSLog(@"Unresolved error: %@ %@", error, [error userInfo]);
}
- (NSInteger) numberOfRowsInTableView:(NSTableView *)aTableView
{
return [self.fetchedResultsController count];
}
- (id) tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex
{
return [self.fetchedResultsController objectAtIndex:rowIndex];
}
- (void) controller:(SNRFetchedResultsController *)controller didChangeObject:(id)anObject atIndex:(NSUInteger)index forChangeType:(SNRFetchedResultsChangeType)type newIndex:(NSUInteger)newIndex
{
switch (type) {
case SNRFetchedResultsChangeDelete:
[self.tableView removeRowsAtIndexes:[NSIndexSet indexSetWithIndex:index] withAnimation:NSTableViewAnimationSlideLeft];
break;
case SNRFetchedResultsChangeInsert:
[self.tableView insertRowsAtIndexes:[NSIndexSet indexSetWithIndex:newIndex] withAnimation:NSTableViewAnimationSlideDown];
break;
case SNRFetchedResultsChangeUpdate:
[self.tableView reloadDataForRowIndexes:[NSIndexSet indexSetWithIndex:index] columnIndexes:[NSIndexSet indexSetWithIndex:0]];
break;
case SNRFetchedResultsChangeMove:
[self.tableView removeRowsAtIndexes:[NSIndexSet indexSetWithIndex:index] withAnimation:NSTableViewAnimationSlideLeft];
[self.tableView insertRowsAtIndexes:[NSIndexSet indexSetWithIndex:newIndex] withAnimation:NSTableViewAnimationSlideDown];
break;
default:
break;
}
}
SNRFetchedResultsController
is created by Indragie Karunaratne. He has been rocking the Mac OS X open source stuff lately and this latest one doesn't disappoint.