Skip to content

Instantly share code, notes, and snippets.

@Frankacy
Created November 15, 2016 04:43
Show Gist options
  • Save Frankacy/5e1fce74e9b0350e3c0f325e35ac8880 to your computer and use it in GitHub Desktop.
Save Frankacy/5e1fce74e9b0350e3c0f325e35ac8880 to your computer and use it in GitHub Desktop.
Data Providers and Presenters
#import <CoreData/CoreData.h>
#import "FRKDataProvider.h"
@interface FRKCoreDataProvider : NSObject <FRKDataProvider, FRKSectionInfoProvider>
- (instancetype)initWithFetchRequest:(NSFetchRequest *)fetchRequest moc:(NSManagedObjectContext *)fetchMOC;
- (instancetype)initWithFetchRequest:(NSFetchRequest *)fetchRequest moc:(NSManagedObjectContext *)fetchMOC sectionKeypath:(NSString *)section;
@end
#import "FRKCoreDataProvider.h"
@interface FRKCoreDataProvider ()
@property(nonatomic, strong) NSFetchedResultsController *fetchedResultsController;
@property(nonatomic, strong) NSManagedObjectContext *fetchingMOC;
@property(nonatomic, strong) NSFetchRequest *fetchRequest;
@property(nonatomic, copy) NSString *sectionKeypath;
@end
@implementation FRKCoreDataProvider
- (instancetype)initWithFetchRequest:(NSFetchRequest *)fetchRequest
moc:(NSManagedObjectContext *)fetchMOC {
return [self initWithFetchRequest:fetchRequest moc:fetchMOC sectionKeypath:nil];
}
- (instancetype)initWithFetchRequest:(NSFetchRequest *)fetchRequest
moc:(NSManagedObjectContext *)fetchMOC
sectionKeypath:(NSString *)section {
self = [super init];
if (!self) {
return nil;
}
_fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
managedObjectContext:fetchMOC
sectionNameKeyPath:section
cacheName:nil];
return self;
}
#pragma mark - FRKDataProvider
- (void)loadDataWithCompletion:(void (^)(NSArray *errors))completion {
NSError *error;
BOOL success = [self.fetchedResultsController performFetch:&error];
if (success) {
completion(nil);
} else {
NSLog(@"Something isn't right :(");
completion(error);
}
}
- (id)itemAtIndexPath:(NSIndexPath *)indexPath {
return [self.fetchedResultsController objectAtIndexPath:indexPath];
}
- (NSIndexPath *)indexForItem:(id)item {
return [self.fetchedResultsController indexPathForObject:item];
}
#pragma mark - FRKSectionInfoProvider
- (NSInteger)numberOfSections {
return [[self.fetchedResultsController sections] count];
}
- (NSInteger)numberOfItemsInSection:(NSInteger)section {
id <NSFetchedResultsSectionInfo> sectionInfo = [self.fetchedResultsController.sections objectAtIndex:section];
return [sectionInfo numberOfObjects];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment