user722361
user722361

Reputation: 11

Coredata NSPredicate by date

I am using XCode 4 & IOS 4.3

LastWorn is a Date attribute in a coredata model. In the objective C class LastWorn is an NSDate. Using objective-c I can set and get the date to and from the coredata database ok. btnSearchOperator contains > or < datePicker.date is the current selected value of a UIDatePicker

I am trying to search a coredata database using the LastWorn date in a predicate. Extract from code that builds the NSPredicate to query the data

... code not shown ...
if ([txtSearchDate.text length] > 0 )
{
    if ([predicate length] != 0) {
        [predicate appendString:@" AND "];
    }
    [predicate appendFormat:@"LastWorn %@ %@", [btnSearchOperator currentTitle], datePickerView.date];        
}

The above code appends 'LastWorn > 2011-04-20 14:00:00 +0000' to the predicate and it crashes.

Console log 2011-04-23 22:34:17.805 iDresser[1216:207] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse the format string "Type.Id == 0 AND Shopping == NO AND (LastWorn > 2011-04-20 14:00:00 +0000)"'

If I use the F-Script CoreData Browser Tool and build a test query "LastWorn != nil" shows the correct results.

If I query "LastWorn > 2011-01" it shows the same as LastWorn != nil and is not correct.

If I query "LastWorn > 2011" I get "NSInvalidArgumentException: -[NSCFNumber timeIntervalSinceReferenceDate]: unrecognized selector sent to instance 0x20048a920"

I simply want to find all items with a LastWorn date less than a specified value? Any suggestions would be appreciated.

Upvotes: 1

Views: 1782

Answers (1)

lorenzo
lorenzo

Reputation: 1743

I ran into the same problem, you need to build your predicate using:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"LastWorn %@ %@", [btnSearchOperator currentTitle], datePickerView.date]

It fails if you build your predicate in a string and then set it to the predicate

Upvotes: 2

Related Questions