复合谓词不适用于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个商家。以下是merchantsForDisplay在循环和登录时的样子。。。

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

我完全不明白为什么我的"ANY categories.categoryId IN%@"不起作用。帮助

将结果限制为具有给定类别的对象,您必须在中使用andPredicateWithSubpredicates,而不是orPredicateWithSubpredicates

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

备注:我建议在建筑时根本不要使用stringWithFormat谓词,因为它以不同的方式处理引用、转义和格式说明符来自CCD_ 4。

最新更新