How do I do this NSPredicate code?

2019-08-13 22:04发布

I'm having trouble with NSPredicate. I have a core data object called Entry, which contains an NSDate called creationDate. I want to compare this to the variable I have called date.

I'm using an NSDate category to pull out the individual year of both objects, and a core data category to perform a predicate on all Entry objects in my core data store.

[Entry allForPredicate:[NSPredicate predicateWithFormat:@"creationDate.year == %i",  date.year]];

I think this is wrong, as it's not giving me the result I expect, and is instead turning up blank.

Where am I going wrong with this?

2条回答
SAY GOODBYE
2楼-- · 2019-08-13 22:48

I doubt, Core Data can incorporate Categories when it creates the raw database call.

For your case create 2 dates, one with January the 1st this year at 0:00 and one year later

 NSString *basePredicateString = @"creationDate >= %@ AND creationDate < %@";
 NSPredicate *predicate = [NSPredicate predicateWithFormat:basePredicateString, startDate, endDate];

for the sake of completeness — How I would generate the start & end date for the actual year:

NSDate *startDate = [NSDate date];
[[NSCalendar currentCalendar] rangeOfUnit:NSYearCalendarUnit startDate:&startDate interval:NULL forDate:startDate];

NSDateComponents *comps = [[[NSDateComponents alloc] init] autorelease];
comps.year = 1;
NSDate *endDate = [[NSCalendar currentCalendar] dateByAddingComponents:comps toDate:startDate options:0];

In the comments below this answer, jbrennan proposed, that indeed a category can be incorperated into a predicate. While he is right for collections as NSArrays (he added a link to a test project), it does not work when it comes to Core Data fetch requests — at least I cannot make it work. I tried. Here is my test: https://github.com/vikingosegundo/CoreDataCategoryTest

查看更多
放我归山
3楼-- · 2019-08-13 22:53

@vikingosegundo has the right answer - you can't use categories in a predicate.

If you understand SQL, try setting the following "Argument passed on launch":

-com.apple.CoreData.SQLDebug 1

this will allow you to see the SQL generated by the request. This should help you see how the predicate you write is translated into SQL.


Edit Per @vikingosegundo again - the above applies when used with CoreData per the OP's question.

查看更多
登录 后发表回答