Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSFetchRequest and predicateWithBlock

I am playing with an app that uses Core Data and NSManagedObjects to populate a UITableView. There is only one class in my application, called Event. I have created the following custom instance method on Event:

- (BOOL)isExpired {     return ([[self.endOn dateAtEndOfDay] timeIntervalSinceNow] < 0); } 

I would like to limit the UITableView that displays Event objects to only the Events that are expired - that is, where isExpired returns YES. I have tried to do this by adding an NSPredicate to the NSFetchRequest:

NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary * bindings) {return([evaluatedObject isExpired]);}]; [fetchRequest setPredicate:predicate]; 

but I get the error: *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Problem with subpredicate BLOCKPREDICATE(0x272ac)' ***. Does this mean that you can't use a block predicate with an NSFetchRequest? Or have I just constructed it improperly?

Thank you!

like image 310
Bill Smithed Avatar asked Aug 22 '10 20:08

Bill Smithed


2 Answers

So, it appears that we've established in the comments to the original post that this is likely caused by SQLite stores being incompatible with block predicates, since Core Data cannot translate these to SQL to run them in the store (thanks, JoostK).

There might be a couple of ways to overcome this:

  • Provided that the end date of your entities is a regular attribute, you might be able to express the expiry constraint as a predicate format string instead of a block predicate, which Core Data should be able to translate into a SQL clause.
  • If the above is possible, you will probably prefer to use a fetch request template to retrieve the expired items. You would need to pass in a substitution variable like $NOW to give access to the current date, though. This has the advantage of making the predicate template show up in the model editor.
  • Both approaches, however, have the disadvantage of duplicating existing functionality (i.e., your isExpired method). So another way would be fetch all qualifiying entities regardless of their expiry state first, and then run a dedicated filtering step on the resulting set of entities to weed out the non-expired ones. Since by that point, they have been fully resurrected from the store, you should be able to use a block predicate for this.
like image 108
ig2r Avatar answered Sep 17 '22 13:09

ig2r


You can do a normal fetch request without specifying the predicate, and afterwards filter the resulting array:

NSArray *allEvents = [context executeFetchRequest:fetchRequest];  if (!allEvents) { // do error handling here }  NSArray *expiredEvents = [allEvents filteredArrayUsingPredicate:predicate]; 
like image 40
Victor Jalencas Avatar answered Sep 21 '22 13:09

Victor Jalencas