NSFetchRequest and predicateWithBlock

后端 未结 2 1352
春和景丽
春和景丽 2020-11-30 05:51

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 c

相关标签:
2条回答
  • 2020-11-30 06:21

    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];
    
    0 讨论(0)
  • 2020-11-30 06:39

    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.
    0 讨论(0)
提交回复
热议问题