Search code examples
iosuitableviewcore-datansfetchedresultscontroller

Core Data and Table Views


Scenario :

I have an expense tracking iOS Application and I am storing expenses from a expense detail view controller into a table view that shows the list of expenses along with the category and amount.

On the top of the tableview, is a UIView with CALENDAR button, a UILabel text showing the date (for example: Oct 23, 2012 (Sun)) and 2 more buttons on the side. The pressing of the calendar button opens up a custom calendar with the current date and the two buttons are for decrementing and incrementing the date correspondingly.

I want to save the expenses according to the date which is an attribute in my Core data entity "Expense".

Question: Suppose I press the calendar button and choose some random date from there, the table view underneath it, should show that day's particular expenses. What I mean is I want the table view to just show a particular date's expenses and if I press the button for incrementing the date or decrementing the date, the table view should show that day's expenses. I am using NSFetchedResultsController and Core Data in order to save my expenses.

Any thoughts on how I would achieve this? Here's the code for FRC.

-(NSFetchedResultsController *)fetchedResultsController

{

if(_fetchedResultsController != nil)
{
return _fetchedResultsController;
}

AppDelegate * applicationDelegate = (AppDelegate *) [[UIApplication sharedApplication] delegate];
NSManagedObjectContext * context = [applicationDelegate managedObjectContext];

NSFetchRequest * request = [[NSFetchRequest alloc]init];

[request setEntity:[NSEntityDescription entityForName:@"Money" inManagedObjectContext:context]];

NSSortDescriptor *sortDescriptor1 =
[[NSSortDescriptor alloc] initWithKey:@"rowNumber"
                        ascending:YES];

NSArray * descriptors = [NSArray arrayWithObjects:sortDescriptor1, nil];

[request setSortDescriptors: descriptors];
[request setResultType: NSManagedObjectResultType];
[request setIncludesSubentities:YES];

[sortDescriptor1 release];

self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request
                                                                  managedObjectContext:context
                                                                  sectionNameKeyPath:nil
                                                                           cacheName:nil];
self.fetchedResultsController.delegate = self;

[request release];

NSError *anyError = nil;

if(![_fetchedResultsController performFetch:&anyError])
{
NSLog(@"error fetching:%@", anyError);
} 

return _fetchedResultsController;
}

Thanks guys.


Solution

  • You would have to create a new NSFetchedResultsController with a new NSFetchRequest that has an appropriately set NSPredicate:

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(date == %@)", dateToFilterFor];
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    // Edit the entity name as appropriate.
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Expense" inManagedObjectContext:self.managedObjectContext];
    [fetchRequest setEntity:entity];
    [fetchRequest setPredicate:predicate];
    
    // ...
    
    NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:@"SomeCacheName"];
    aFetchedResultsController.delegate = self;
    self.fetchedResultsController = aFetchedResultsController;
    

    Don't forget to call [self.tableView reloadData]; after assigning the new FRC.

    Edit: You can assign a predicate to an NSFetchRequest which then is assigned to the fetchedResultsController. You can think of the predicate as a filter.

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(date == %@)", dateToFilterFor];
    

    If you add this to the fetch request by calling [fetchRequest setPredicate:predicate]; you tell the fetched request to only fetch results where to date property of the NSManagedObject matches the date you provide in the predicate. Which is exactly what you want here.

    So if you have a method that's called after the user selected a date you could modify it like this:

    - (void)userDidSelectDate:(NSDate *)date
    {
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        // Edit the entity name as appropriate.
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"Event" inManagedObjectContext:self.managedObjectContext];
        [fetchRequest setEntity:entity];
    
    
        //Here you create the predicate that filters the results to only show the ones with the selected date
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(date == %@)", date];
        [fetchRequest setPredicate:predicate];
    
        // Set the batch size to a suitable number.
        [fetchRequest setFetchBatchSize:20];
    
        // Edit the sort key as appropriate.
        NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"timeStamp" ascending:NO];
        NSArray *sortDescriptors = @[sortDescriptor];
    
        [fetchRequest setSortDescriptors:sortDescriptors];
    
        // Edit the section name key path and cache name if appropriate.
        // nil for section name key path means "no sections".
        NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:@"Master"];
       aFetchedResultsController.delegate = self;
    
       //Here you replace the old FRC by this newly created
       self.fetchedResultsController = aFetchedResultsController;
    
    
       NSError *error = nil;
       if (![self.fetchedResultsController performFetch:&error]) {
         // Replace this implementation with code to handle the error appropriately.
         // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
       }
    
       //Finally you tell the tableView to reload it's data, it will then ask your NEW FRC for the new data
       [self.tableView reloadData];
    
    
    }
    

    Notice that if you're not using ARC (which you should) you'd have to release the allocated objects appropriately.