iOS Simple Predicate'包含'不起作用

时间:2013-04-11 03:38:17

标签: ios core-data predicate

我有一个模特:

地方< --->>类别

执行以下查询时:

NSFetchRequest *req = [NSFetchRequest fetchRequestWithEntityName:@"Category"];
if(![searchText isEqualToString:@""] && searchText != nil){
    req.predicate = [NSPredicate predicateWithFormat:@"(places.placeTitle contains %@) OR (places.details contains %@) OR (name contains %@)", searchText, searchText, searchText];
    NSLog(@"ModelHelper.getResults: Search text given, creating predicate: %@", req.predicate);
}
req.sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"name"
                                                                             ascending:YES
                                                                              selector:@selector(localizedCaseInsensitiveCompare:)]];
NSFetchedResultsController *controller = [[NSFetchedResultsController alloc]initWithFetchRequest:req
                                                                            managedObjectContext:context
                                                                              sectionNameKeyPath:nil
                                                                                       cacheName:nil];
NSError *error = nil;
[controller performFetch:&error];

我收到不应该存在的匹配项,例如:

searchText = "1234"

第一个结果是:

category[0].name = "Bars"
category[0].places[0].placeTitle = "Aaa"
category[0].places[0].details = "Aaa"
category[0].places[1].placeTitle = "123456"
category[0].places[1].details = "123456"
category[0].places[2].placeTitle = "test"
category[0].places[2].details = "test"

我的谓词是否有问题?感谢。

1 个答案:

答案 0 :(得分:1)

来自documentation

  
    

重要说明:调用此方法后,不得修改fetchRequest。例如,您不得更改其谓词或排序顺序。

  

移动此段:

if(![searchText isEqualToString:@""] && searchText != nil){
    req.predicate = [NSPredicate predicateWithFormat:@"(places.placeTitle contains[c] %@) OR (places.details contains[c] %@) OR (name contains[c] %@)", searchText, searchText, searchText];
    NSLog(@"ModelHelper.getResults: Search text given, creating predicate: %@", req.predicate);
}

在初始化FRC之前