2013-04-11 47 views
1

我有一個模型:的iOS簡單謂 '包含' 不工作

地方< --- >>類別

當執行下面的查詢:

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" 

有沒有我做錯了我的謂詞?謝謝。

+0

req.predicate = [NSPredicate predicateWithFormat:@「(places.placeTitle包含%@)或(地方CONTAINS%@)或(名稱CONTAINS%@)「,searchText,searchText,searchText]; – 2013-04-11 03:41:27

回答

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

+0

謝謝。我試着改變你的建議(如上面更新代碼所示),但我仍然得到完全相同的行爲。 – wuntee 2013-04-11 06:56:46

+0

但您的結果與謂詞匹配:places [2] .placeTitle =「1234 ...」 – 2013-04-11 07:28:24

+0

是的,結果中包含的項目不匹配。地點[1]沒有標題或與「1234」匹配的詳細信息。 – wuntee 2013-04-11 13:18:54