I have a UITable view which contains a list of NSManagedObjects called Assignment. I am using NSPredicate to filter the list. I am filtering assignments that should be shown for today and yesterday for a player:
NSPredicate *predicate = [NSPredicate predicateWithFormat:
@"player == %@ AND (day == %@ OR day == %@)",
player,
[NSNumber numberWithInt:[self todaysDayNumber]],
[NSNumber numberWithInt:[self yesterdaysDayNumber]]];
I need to add an additional level of filtering. I want to filter out assignments that should only be shown biweekly. So I added this methods to Assigment: 开发者_如何学编程
-(BOOL)thisWeeks{
//If this is a weekly assigment
if ([self.weekly boolValue]) {
return YES;
}
//Determine the week number
NSCalendar *calendar = [NSCalendar currentCalendar];
NSUInteger unitFlags = NSWeekCalendarUnit;
NSDateComponents *dateComponents = [calendar components:unitFlags
fromDate:[NSDate date]];
NSUInteger week = [dateComponents week];
//Assigned week even?
if ([self.weekNumber intValue] % 2){
//Current week even?
if (week % 2) {
return YES;
}
}
//Assigned week odd?
if (!week % 2) {
//Current week odd?
if (![self.weekNumber intValue] % 2){
return YES;
}
}
//Should not be shown this week.
return NO;
}
is it possible to use this helper method "thisWeeks" as a filter in NSPredicate?
If I'm "doing it wrong", I could manually filter the fetched results, but I am unsure as to how I would put the results back into NSFetchedResultsController such that my UITable view could continue using NSFetchedResultsController.
NSPredicate also accepts blocks as predicates. Here an example with the first check in thisWeeks:
NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(id obj, NSDictionary *bind) {
return [self.weekly boolValue];
}];
Now you can implement the method - (BOOL)thisWeeksWithObject:(id)object and write this:
NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(id obj, NSDictionary *bind) {
return [self thisWeeksWithObject:obj];
}];
Sure, you have to change the self in the method to object.
精彩评论