Reputation: 4843
I have a CoreData entity Comment
who has a parent entity Measurement
.
The Measurement
entity has a measurementDate
attribute.
My Core Data database has 200 Comment
records in it, each with varying measurementDate
values over the last 3 years.
I'm trying to get the records where measurementDate
is between any two given dates.
Firstly, I tried this:
//now fetch a record between 12 and 11 months ago
NSDate *startDate = [AppGlobals dateByAddingMonths:[NSDate date] withMonths:-12];
NSDate *endDate = [AppGlobals dateByAddingMonths:startDate withMonths:1];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(measurementDate >= %@) AND (measurementDate <= %@)", startDate, endDate];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"Comment" inManagedObjectContext:self.context]];
[request setPredicate:predicate];
NSError *error = nil;
NSArray *results = [self.context executeFetchRequest:request error:&error];
But I got 0 results.
So then I tried replacing my predicate with something simpler:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"measurementDate >= %@", startDate];
This should return approximately a third of my results. But actually it returns ALL 200 RECORDS.
I've logged out the dates of the objects and it looks like the dates are being completely ignored!
What am I doing wrong???
Is it something to do with the Parent Abstract entity Measurement
and because I'm fetching from the Comment
entity and not the Measurement
entity?
Is it because I'm using "scalar properties for primitive data types" in my code?
Any help greatly appreciated.
Upvotes: 2
Views: 1908
Reputation: 6715
You should either use NSDate
or use NSTimeInterval
(primitive, since it’s really a double
).
If you mix those, you’ll easily confuse yourself. Basically, an NSDate
object is a class that wraps an NSTimeInterval
value, i.e. a double
-- nothing more. And NSDate
adds lots of methods for working on that value.
The compiler should have given you a slew of warnings, though.
Upvotes: 0
Reputation: 539685
I assume that the problem is where you assign the date value to the managed object. If measurementDate
is defined as scalar property
@property (nonatomic) NSTimeInterval measurementDate;
then you assign an NSDate
to it with
NSDate *theDate;
obj.measurementDate = [theDate timeIntervalSinceReferenceDate];
Upvotes: 5