Search code examples
iosuitableviewcore-datansfetchrequest

How to make index list table view with Core Data, iOS Dev


I have an Entity in core data called "Expense" with attributes "Date, Category, Amount..........". How can I list all the expenses with index list, based on "Year-Month" from Date attribute?

From apple's document and tutorials, I know how to make index list table view. But it requires to provide "Array of arrays". That's one array for all sections, and one sub-array for objects in one specific section. Now my data structure is not like this.

From my thinking, what I can do is:

  1. fetch all the expenses first, then extract all cases of "Year-Month" with no duplication, put them into an array, which is for all the sections
  2. then I fetch all the expenses based on every section

But I think it's kind of heavy work, can I achieve this more conveniently? Or should I change my data structure ? Thank you guys :)


Solution

  • You could create a request to return only the expenses in the given range:

    //Not tested
    NSDateComponents* comps = [[NSDateComponents alloc] init];
    NSCalendar* cal = [NSCalendar currentCalendar];
    NSInteger year,month;//set these as you like
    [comps setYear:year];
    [comps setMonth:month];
    NSDate* start = [cal dateFromComponents:comps];
    month += 1;
    month = (month <= 12 ? : 1);
    [comps setMonth:month];
    NSDate* end = [cal dateFromComponents:comps];
    NSPredicate* predicate = [NSPredicate predicateWithFormat:@"date > %@ AND date < %@",start,end];
    NSFetchRequest* request = [[NSFetchRequest alloc] initWithEntityName:@"Expense"];
    [request setPredicate:predicate];
    

    Then use a NSFetchedResultsController to populate your table view