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