However, if you need more complex fetching eg. limit fetch results, then you need to use NSFetchRequest directly.
1234567891011121314
-(NSFetchedResultsController*)fetchedResultsController{if(_fetchedResultsController!=nil){return_fetchedResultsController;}NSFetchRequest*fetchRequest=[PoorequestAllSortedBy:@"pooedOn"ascending:NO];[fetchRequestsetFetchLimit:100];// Let's say limit fetch to 100[fetchRequestsetFetchBatchSize:20];// After 20 are faultedNSFetchedResultsController*theFetchedResultsController=[[NSFetchedResultsControlleralloc]initWithFetchRequest:fetchRequestmanagedObjectContext:[NSManagedObjectContextdefaultContext]sectionNameKeyPath:nilcacheName:@"PooCache"];self.fetchedResultsController=theFetchedResultsController;self.fetchedResultsController.delegate=self;return_fetchedResultsController;}
Perform a fetch in viewDidLoad
1234567891011
-(void)viewDidLoad{[superviewDidLoad];// Delete cache first, if a cache is used[NSFetchedResultsControllerdeleteCacheWithName:@"PooCache"];NSError*error;if(![[selffetchedResultsController]performFetch:&error]){// Update to handle the error appropriately.NSLog(@"Unresolved error %@, %@",error,[erroruserInfo]);}}
Table view data source
123456789101112131415161718
-(NSInteger)numberOfSectionsInTableView:(UITableView*)tableView{return[[_fetchedResultsControllersections]count];}-(NSInteger)tableView:(UITableView*)tableViewnumberOfRowsInSection:(NSInteger)section{idsectionInfo=[[_fetchedResultsControllersections]objectAtIndex:section];return[sectionInfonumberOfObjects];}-(UITableViewCell*)tableView:(UITableView*)tableViewcellForRowAtIndexPath:(NSIndexPath*)indexPath{staticNSString*CellIdentifier=@"PooCell";UITableViewCell*cell=[tableViewdequeueReusableCellWithIdentifier:CellIdentifierforIndexPath:indexPath];// Configure the cell[selfconfigureCell:cellatIndexPath:indexPath];returncell;}
Helper method to configure cell
12345
-(void)configureCell:(UITableViewCell*)cellatIndexPath:(NSIndexPath*)indexPath{Poo*poo=[self.fetchedResultsControllerobjectAtIndexPath:indexPath];// Update cell with poo detailscell.textLabel.text=poo.title;}
Deleting
12345678910111213
-(void)tableView:(UITableView*)tableViewcommitEditingStyle:(UITableViewCellEditingStyle)editingStyleforRowAtIndexPath:(NSIndexPath*)indexPath{if(editingStyle==UITableViewCellEditingStyleDelete){// The correct way to save (http://samwize.com/2014/03/29/how-to-save-using-magicalrecord/)Poo*poo=[self.fetchedResultsControllerobjectAtIndexPath:indexPath];[MagicalRecordsaveWithBlock:^(NSManagedObjectContext*localContext){Poo*localPoo=[pooinContext:localContext];[localPoodeleteEntity];}];}elseif(editingStyle==UITableViewCellEditingStyleInsert){// Create a new entity and save}}
The 4 Crazy NSFetchedResultsControllerDelegate methods