How do I do this NSPredicate code?

限于喜欢 提交于 2020-01-16 00:56:08

问题


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?


回答1:


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




回答2:


@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.



来源:https://stackoverflow.com/questions/10954273/how-do-i-do-this-nspredicate-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!