JimZ
JimZ

Reputation: 1202

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

Upvotes: 0

Views: 362

Answers (2)

Matt
Matt

Reputation: 2411

This is a very general question, but the basic idea is to use an NSFetchedResultsController to display the data and an NSPredicate to do the filtering.

I'd also strongly recommend you have a look at frameworks such as Sensible TableView as it will be able to help you automatically display and filter out of the box.

Upvotes: 0

Dan Shelly
Dan Shelly

Reputation: 6011

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

Upvotes: 1

Related Questions