使用NSPredicate Core Data

时间:2016-03-08 16:40:59

标签: ios core-data nspredicate

我创建了一种从数据库中恢复产品的方法,每个项目都有字段height,width和percErro(百分比错误),

用户输入您要搜索的宽度和高度,例如:15 x 15cm

然后,该方法应该为这些数字带来兼容的产品,同时考虑到注册时允许的错误百分比。

假设产品的数据库是14 x 14厘米,错误百分比是10%(1.4厘米),那么你搜索一个15 x 15厘米的产品

在我的查询中,我必须做这样的事情:

[query appendString: [NSString stringWithFormat: @ "(heigthInserted * percErro / 1000) <= (height * percErro / 100)"

[query appendString: [NSString stringWithFormat: @ "AND (widthInserted * percErro / 1000) <= (width * percErro / 100)"

 NSPredicate * predicate = [NSPredicate predicateWithFormat: query];
    [Request setPredicate: predicate];

这应该给我带来误差百分比不超过10%(1.4 cm)的所有产品

我知道NSPredicate不接受数学运算,我怎样才能得到计算这个误差百分比的结果?

**

  

解决

**

  

我接受了pbasdf的答案并得出数学结论   运营商在NSPredicate工作,但必须按照   此链接的文档:Documentation

     

低于我的100%功能方法与运营商:

-(NSMutableArray*)findWithDimensoes:(NSMutableArray*)formatos :(float)largura :(float)altura{
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:[NSEntityDescription entityForName:TABLE_NAME inManagedObjectContext:managedObjectContext]];

    NSSortDescriptor *sortDescriptor1 = [[NSSortDescriptor alloc] initWithKey:@"altura" ascending:YES];
    NSSortDescriptor *sortDescriptor2 = [[NSSortDescriptor alloc] initWithKey:@"largura" ascending:YES];

    NSArray *arraySD = [NSArray arrayWithObjects:sortDescriptor1,sortDescriptor2,nil];
    [request setSortDescriptors:arraySD];
    [request setFetchLimit:20];

    NSMutableString *query = [[NSMutableString alloc] init];

    [query appendString:[NSString stringWithFormat:@" (habilitado == true) "]];

    if (formatos != nil) {
        for (ProdutoDimensao *d in formatos) {
            if ([d.id intValue] > 0) {
               if (([formatos indexOfObject:d] < formatos.count)) {
                    [query appendString:@" AND "];
                }

                [query appendString:[NSString stringWithFormat:@" (produtoDimensao.id == %d) ",[d.id intValue]]];
            }
        }
    }

    [query appendString:[NSString stringWithFormat:@" AND altura >=  from:subtract:(%lf,multiply:by:(%lf,percErro)) AND altura <= add:to:(%lf,multiply:by:(%lf,percErro)) ",altura,altura,altura,altura]];
[query appendString:[NSString stringWithFormat:@" AND largura >=  from:subtract:(%lf,multiply:by:(%lf,percErro)) AND largura <= add:to:(%lf,multiply:by:(%lf,percErro)) ",largura,largura,largura,largura]];


    NSPredicate *predicate = [NSPredicate predicateWithFormat:query];
    [request setPredicate:predicate];

    NSError *error = nil;
    NSArray *results = [managedObjectContext executeFetchRequest:request error:&error];


    return [results mutableCopy];

}

0 个答案:

没有答案