复合谓词不能使用MagicalRecord Fetch

时间:2013-11-27 18:44:14

标签: objective-c core-data magicalrecord

我的数据模型如下......

MNMerchant< - (关系类别) - >> MNCategory(categoryId)

MNCategory与MNMerchant的反向关系称为“商家”。

我的视图控制器在地图视图上显示商家。第一次按地图边界限制结果的提取工作正常......

NSMutableArray *filters = [NSMutableArray array];

NSMutableString *rectPred = [NSMutableString stringWithFormat:@"lng > %lf AND lng < %lf AND lat < %lf AND lat > %lf", northWestCorner.longitude, southEastCorner.longitude, northWestCorner.latitude, southEastCorner.latitude];

[filters addObject:[NSPredicate predicateWithFormat:rectPred]];

NSArray *merchantsInRect = [[MNMerchant MR_findAll] filteredArrayUsingPredicate:[NSCompoundPredicate orPredicateWithSubpredicates:filters]];

我的样本/测试数据正确返回3个商家。这是日志输出......

FILTERS = (
    "lng > -105.961313 AND lng < -104.2035 AND lat < 41.048607 AND lat > 38.927436"
)
RESULTS = 3 MERCHANTS IN RECT

然后,我获取已获取商家的类别,并填充用于按类别过滤地图的菜单。该菜单仅显示所显示的地图地理范围内商家的有效类别。

NSMutableArray *categories = [NSMutableArray arrayWithObjects:nil];
for(MNMerchant *merchant in merchantsInRect){
    for(MNCategory *category in merchant.categories){
        if([categories indexOfObject:category] == NSNotFound){
            [categories addObject:category];
        }
    }
}

[_tray setCategories:categories];

然后,用户可以关闭这些类别,这样就可以使用附加的一组过滤器进行第二次获取...

NSArray *merchantsForDisplay;

if(useFilters){
    //FILTER MERCHANTS
    if(_tray.selectedCategories.count == 0){
        [filters addObject:[NSPredicate predicateWithFormat:@"merchantId = 0"]];
    }else{
        [filters addObject:[NSPredicate predicateWithFormat:@"ANY categories.categoryId IN %@", [_tray.selectedCategories valueForKey:@"categoryId"]]];
    }

    merchantsForDisplay = [MNMerchant MR_findAllSortedBy:@"sortName" ascending:YES withPredicate:[NSCompoundPredicate orPredicateWithSubpredicates:filters]];

}else{

    merchantsForDisplay = merchantsInRect;

}

启用和禁用类别时记录的输出...

FILTERS = (
    "lng > -105.980539 AND lng < -104.222726 AND lat < 40.959464 AND lat > 38.835483",
    "ANY categories.categoryId IN {2}"
)
RESULTS = 3 MERCHANTS IN RECT

但是,此提取不会过滤到所选类别。它仍在返回3个商家。循环和记录时,这就是商品ForDisplay的样子......

MERCHANT 16695
...HAS CATEGORY 1
MERCHANT 16719
...HAS CATEGORY 1
...HAS CATEGORY 2
MERCHANT 16712
...HAS CATEGORY 1

我完全不知道为什么我的“任何categories.categoryId IN%@”无效。救命啊!

1 个答案:

答案 0 :(得分:1)

结果限制为具有给定类别的对象,您必须这样做

中使用andPredicateWithSubpredicates,而不是orPredicateWithSubpredicates
merchantsForDisplay = [MNMerchant MR_findAllSortedBy:@"sortName" ascending:YES withPredicate:[NSCompoundPredicate orPredicateWithSubpredicates:filters]];

备注:我建议在构建时不要使用stringWithFormat 谓词,因为它以不同方式处理引用,转义和格式说明符 来自predicateWithFormat