Reputation: 31
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 :
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
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
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