Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
496 views
in Technique[技术] by (71.8m points)

ios - Core Data NSPredicate not returning records between two dates

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...