pravi
pravi

Reputation: 31

filtering array of core data objects for specific date or year or month or date range

I have an array of objects and one property of this array is NSDate. I need to create function to filter those objects based on specific date

Like :

  1. Filter array for year 2013
  2. Filter array for date 12-mar-13
  3. Filter array for month feb 2012
  4. Filter array within range date

pls get me a solution or suggest me a better way of data management in core data to achieve this ...

thanks in advance

Upvotes: 0

Views: 1886

Answers (2)

Rakesh
Rakesh

Reputation: 3399

You can use NSPredicate to filter the results when you fetch from core-data store. Also after fetching from the core-data store, you can use NSPredicate to filter (like filtering any array).

While fetching from core-data you can use it like below:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(date >= %@) AND (date <= %@)", startDate, endDate];
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:[NSEntityDescription entityForName:@"EntityName" inManagedObjectContext:moc]];
[request setPredicate:predicate];

NSError *error = nil;
NSArray *results = [moc executeFetchRequest:request error:&error];

This code is from here.

And when using predicate to filter an array use the array instance method filteredArrayUsingPredicate: with predicate created as in the above code to filter your array.

The thing when using date in predicate is that date object store time data as well so you might want to check in a range of time like midnight to midnight or from 00:00 to 23:59. Something like that, depending on what you want to compare.

Upvotes: 1

Mundi
Mundi

Reputation: 80273

You should use an NSPredicate. You can filter your results array or include the predicate directly into your NSFetchRequest.

/* 1 */ [NSPredicate predicateWithFormat:@"date > %@ && date < %@", 
          firstDayOfYear, lastDayOfYear];
/* 2 */ [NSPredicate predicateWithFormat:@"date > %@ && date < %@", 
          startMarch12, endMarch12];
/* 3 */ [NSPredicate predicateWithFormat:@"date > %@ && date < %@", 
          startFeb2012, endFeb2012];
/* 4 */ [NSPredicate predicateWithFormat:@"date > %@ && date < %@", 
          startDate, endDate];

Upvotes: 0

Related Questions