NSPredicate:使用filteredArrayUsingPredicate过滤NSDateComponents数组时发送到实例的无法识别的选择器

时间:2014-09-05 20:20:32

标签: ios nsarray nsdate nspredicate nsdatecomponent

我有一些代码,其中我从现在到一年都有一系列日期

        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];
        }

我需要使用另一个日期组件数组来过滤该数组(dateComponentsInRange),比较日,月和年。

到目前为止,我试过这个

        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];

但是我收到以下错误

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

2 个答案:

答案 0 :(得分:3)

您正在向数组添加字符串并将其用作谓词。

尝试:

    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];

答案 1 :(得分:1)

根据Apple文档orPredicateWithSubpredicates需要一个NSPredicate数组,但您传递的是NSString个数组。

错误说

  
    

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

  

这是正确的,因为evaluateWithObject:substitutionVariables没有为NSString定义NSPredicate

Src:Apple文档