2
votes

I currently have a FRC for my sections which are loaded from a transient property.

I'd like to let the user limit what he sees to for example one specific month.

I read an answer somewhere that said to add a method because the predicate calls it so I tried adding a method to the managed object class .m file like so:

@property (nonatomic) NSInteger monthOfDate;
@synthesize monthOfDate;

-(NSInteger) monthOfDate
{
NSDate *date = [self theDate];
NSDateComponents *components = [[NSCalendar currentCalendar]components: NSCalendarUnitMonth fromDate:date];
NSInteger month = [components month];
return month;
}

but when used in a predicate like so:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"monthOfDate == %d", 6];

I get the error: Keypath monthOfDate not found in entity.

Is this anyhow possible or should I make the month an additional attribute when the date is saved? I read some answers advising to compare a start and end date. But the user will be able to select a wide range of custom dates (a year, a month, weeks, specific day to day) so that seems like a long way to go about this..

1

1 Answers

2
votes

When you do a fetch request, the predicate acts as the SQL query to fetch rows from the table in the database. Those rows haven't been "converted" to Objective-C objects yet, so the method you added is unavailable there. The predicate is looking for columns in the table, meaning attributes of your entity. Your predicate would work perfectly on an array of your NSManagedObject subclass.

So you have two options:

You could just fetch every object of that entity and then perform that predicate on the fetched objects. Which isn't ideal because you're fetching (and storing) more objects than you need and thus waste memory.

Or better, add an addition attribute 'month' to your entity, when writing to your database execute your method and store the month value as a separate attribute in your database. Then simply fetch using a predicate to compare with that attribute.