Search code examples
objective-ccocoanstableviewpredicatenssearchfield

Search records by DATE in NSTableView and CoreData using InterfaceBuilder


I have an NSTableView which pull data from CoreData using ArrayController. In my form, I also have search field.

Search form works just fine if:

  1. I select the search field, and in binding inspector under predicate I bind the search field to the array controller that is used to get the data in the nstableview.

  2. In the predicate format field I add

    customerName contains[cd] $value or customerWebsite contains[cd] $value

So now either I search for customerName (STRING) or customerWebsite (STRING), I get the results just fine.

But, If i change the field with the field which contains DATE, my search doesn't work. For example noting of bellow doesn't work:

contractExpiresOn contains[cd] $value
contractExpiresOn == $value
contractExpiresOn = $value
contractExpiresOn >= $value
contractExpiresOn > $value
contractExpiresOn %LIKE $value
//contractExpiresOn is DATE

When I search using the above predicate formats, the app doesn't crash, but no results are returned, even for example I have dates that start with 0, as soon as I type 0 in the search field, NSTableView is empty.

Can anyone tell me how can I make my search to work with dates trough interface builder, or if that is not possible, how can I do that programatically.


Solution

  • You can't compare a date with a string and you have to do some programming. Create a category on NSDate and add a method for converting the date to a string. For example:

    @implementation NSDate(Search)
    
    static NSDateFormatter *searchDateFormatter = nil;
    
    - (NSString *)searchString {
        if (!searchDateFormatter) {
            searchDateFormatter = [[NSDateFormatter alloc] init];
            searchDateFormatter.dateStyle = NSDateFormatterShortStyle;
            searchDateFormatter.timeStyle = NSDateFormatterNoStyle;
        }
        return [searchDateFormatter stringFromDate:self];
    }
    
    @end
    

    The predicate format is birthday.searchString contains $value.