1

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 ?

Mohamed Wasiq
  • 490
  • 4
  • 17

3 Answers3

1

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).

pbasdf
  • 21,386
  • 4
  • 43
  • 75
0

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

Ankit Kushwah
  • 539
  • 4
  • 16
0

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)
Jogendar Choudhary
  • 3,476
  • 1
  • 12
  • 26