Search code examples
iosnsarraynsdatenspredicatensdatecomponent

NSPredicate: unrecognized selector sent to instance when filtering array of NSDateComponents using filteredArrayUsingPredicate


I have some code in which I'm getting an array of dates from now to one year

        NSCalendar* calendar = [NSCalendar currentCalendar];
        NSMutableArray *dateComponentsInRange = [NSMutableArray new];
        NSDate *curDate = [dates objectAtIndex:0];

        while ([curDate timeIntervalSince1970] <= [[dates lastObject] timeIntervalSince1970])
        {
            NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:curDate];
            [dateComponentsInRange addObject:components];
            curDate = [curDate dateWithNextDay];
        }

I need to filter that array(dateComponentsInRange) with another array of date components comparing by day, month, and year.

So far I tried this

        NSDateComponents *components = nil;
        NSMutableArray *predicates = [NSMutableArray array];;
        for (NSDate *currentdate in dates)
        {
            components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:currentdate];
            NSString *preficateFormat = [NSString stringWithFormat:@"(SELF.day  != %d AND SELF.month != %d AND SELF.year != %d)",[components day],[components month], [components year]];
            [predicates addObject:preficateFormat];
        }
        NSPredicate *predicate = [NSCompoundPredicate orPredicateWithSubpredicates:predicates];
        NSArray *filteredArr = [dateComponentsInRange filteredArrayUsingPredicate:predicate];

But I'm getting the following error

 [__NSCFString evaluateWithObject:substitutionVariables:]: unrecognized selector sent to instance

Solution

  • You are adding a string to an array and using it as a predicate.

    Try:

        NSDateComponents *components = nil;
        NSMutableArray *predicates = [NSMutableArray array];;
        for (NSDate *currentdate in dates)
        {
            components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:currentdate];
            NSString *preficateFormat = [NSString stringWithFormat:@"(SELF.day  != %d AND SELF.month != %d AND SELF.year != %d)",[components day],[components month], [components year]];
            NSPredicate * predicate = [NSPredicate predicateWithFormat:preficateFormat];
            [predicates addObject:predicate];
        }
        NSPredicate *predicate = [NSCompoundPredicate orPredicateWithSubpredicates:predicates];
        NSArray *filteredArr = [dateComponentsInRange filteredArrayUsingPredicate:predicate];