【问题标题】:Compound Predicate Not Working with MagicalRecord Fetch复合谓词不适用于 MagicalRecord Fetch
【发布时间】:2013-11-28 02:48:17
【问题描述】:

我的数据模型如下...

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 %@”不起作用。救命!

【问题讨论】:

    标签: objective-c core-data magicalrecord


    【解决方案1】:

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

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

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

    【讨论】:

    • 天啊。这很尴尬。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2019-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-11
    • 1970-01-01
    相关资源
    最近更新 更多