I have a Core data with one entity named 'Cigarette' having a 'time' attribute. In my table View I have to populate each cell with total number of cigarettes for each day. How can this be done with NSFetchedResultsController ?
3 Answers
Apple have a sample app which demonstrates how to get an FRC to group items by date. Sadly it's an old app written in Objective-C, but this question shows broadly how to implement it in Swift.
You also need to modify the standard FRC tableView datasource methods and the FRC's own delegate methods, because rather than wanting a cell for each item, you want a cell for each "group" (ie. date).

- 21,386
- 4
- 43
- 75
-
Thank you for your answer. It gave me some idea to start :) – Mohamed Wasiq Sep 07 '18 at 15:17
To get entities for a particular day you have to use NSPredicate to get desire date entities and apply this Predicate to NSFetchRequest, you will get that date entities only

- 539
- 4
- 16
-
Thanks for your answer. I have updated my question so that it gives clear picture – Mohamed Wasiq Sep 06 '18 at 07:29
-
@MohamedWasiq can you post the fetch request (Code) with question so i can post exact solution (code ) – Ankit Kushwah Sep 06 '18 at 07:39
You can fetch the data using fetchedResultsController
:
obj-c
NSArray *fetchedData = [_fetchedResultsController fetchedObjects];
Swift
guard let quotes = fetchedResultsController.fetchedObjects else { return 0 }
if you have more than 1 entity build a fetchrequest for each entity. Something like this should give you all your objects.
Obj-c
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
NSEntityDescription *entity = [NSEntityDescription entityForName:self.entityName inManagedObjectContext:self.managedObjectContext];
[request setEntity:entity];
NSError *error;
NSArray *results = [self.managedObjectContext executeFetchRequest:request error:&error];
Swift
var request = NSFetchRequest()
var entity = NSEntityDescription.entity(forEntityName: entityName, in: managedObjectContext)
request.entity = entity
var error: Error?
var results = try? managedObjectContext.fetch(request)

- 3,476
- 1
- 12
- 26
-
Thanks for your answer. I have updated my question so that it gives clear picture. – Mohamed Wasiq Sep 06 '18 at 07:29