2012-10-29 94 views
1

我試圖找到一個匹配字符串和一組對象的對象。我的謂詞如下所示:核心數據謂詞對多

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name == %@ and individuals CONTAINS %@", name, individuals]; 

我沒有收到任何匹配。雖然我知道有一個匹配名稱和個人設置的實體。

我的謂詞有什麼問題?

編輯:我設法做了一些進步。現在的問題是,如果我試圖找到一個具有現有組名稱和現有聯繫人的組,即groupname =「test」和individuals.name =「john doe」,並且individuals.contactInfo =「123」,它會正確地找到該組但如果我有一個具有相同組名和相同聯繫人的組+另一個聯繫人,它也會找到我這個我不想要的組。

我只想要與謂詞完全匹配的組。

我現在使用subpredicates通過這樣做:

NSMutableArray *subPredicates = [NSMutableArray initWithCapacity:5]; 
// Add group name to predicate 
[subPredicates addObject:[NSPredicate predicateWithFormat:@"name == %@", name]]; 

for (NSDictionary *contactInfo in individuals) { 

    NSString *name = [contactDict objectForKey:@"name"]; 
    NSString *contactInfo = [contactDict objectForKey:@"contactInfo"]; 

    NSPredicate *individualPredicate = [NSPredicate predicateWithFormat:@"ANY individuals.name LIKE %@ AND any individuals.contactInfo LIKE %@", name, contactInfo]; 

    [subPredicates addObject:individualPredicate]; 
} 

NSPredicate *individualsPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:subPredicates]; 

Group *group = // do the fetch with the predicate 

回答

1

我在手機上打字,但無法驗證它,但下面的謂詞可能會爲你工作:

[NSPredicate predicateWithFormat:@"name == %@ AND SUBQUERY(individuals, $x, $x IN %@)[email protected] == %d", 
    name, individuals, individuals.count]; 

它搜索您可以使用ANY謂詞一組匹配一個對象對於給定名稱的個體是給定集合的超集的對象。

+0

我以爲SUBQUERY可以用來過濾一個基於謂詞的集合。 Apple的例子:(SUBQUERY(居民,$ x,$ x.firstname ==「Jane」&& $ x.lastname ==「Doe」)。@ count!= 0)。我不認爲這將在給定的元素列表上工作。 – diederikh

+0

這個謂詞對我不起作用,如果我有一個包含兩個人的組,這個謂詞將返回這個組,即使我只提供了這個組中的一個人。 –

+0

我想我在另一個線程中找到了我的問題的確切答案,因此我將此答案標記爲已接受。 (在這裏回答:http://stackoverflow.com/a/13086353/294661) –

3

一組對象不能與CONTAINS謂詞匹配。

[NSPredicate predicateWithFormat:@"name == %@ and ANY individuals.name == %@", name, individualName]; 
+1

因此,沒有辦法將「NSSet」與謂詞相匹配? –

+0

我更新了我的代碼,幾乎在那裏我想。你能幫我解決最後一件事嗎? –

+0

如果要匹配集合中的所有元素,可以使用ALL謂詞而不是ANY。 – diederikh