2014-02-21 58 views
0

如何創建一個試圖在數組內的字典中查找對象的NSPredicate?NSPredicate - 在NSArray內查找NSDictionary內的對象

例如:

MyArray { 
[0]: Dictionary { 
       email: [email protected] 
       name: John Smith 
       } 
[1]: Dictionary { 
       email: [email protected] 
       name: Mary Davis 
       } 

} 

我如何檢查,看看是否MYARRAY包含「瑪麗·戴維斯」上的「名稱」字段?

我試圖

NSString *user = @"Mary Davis"; 
NSString *criteria = [NSString stringWithFormat:@"name == '%@'", user]; 
NSPredicate *filter = [NSPredicate predicateWithFormat:criteria]; 
NSArray *results = [collaborators filteredArrayUsingPredicate:filter]; 

NSString *user = @"Mary Davis"; 
NSString *criteria = [NSString stringWithFormat:@"name MATCHES[cd] '%@'", user]; 
NSPredicate *filter = [NSPredicate predicateWithFormat:criteria]; 
NSArray *results = [collaborators filteredArrayUsingPredicate:filter]; 

NSString *user = @"Mary Davis"; 
NSString *criteria = [NSString stringWithFormat:@"object MATCHES[cd] '%@'", user]; 
NSPredicate *filter = [NSPredicate predicateWithFormat:criteria]; 
NSArray *results = [collaborators filteredArrayUsingPredicate:filter]; 

但似乎沒有工作。我知道我可以做

for (int i=0; i (less than) myArray.count; i++){ 
    NSDictionary *dict = [myArray objectAtIndex:i]; 
    if ([[dict objectForKey:@"name"] isEqualToString:user]) 
     return ; 
} 

和它的作品,但我需要這個作謂語,因爲我想用PFQuery queryWithClassName謂詞從Parse.com獲取數據。

是否有可能做到這一點,或者是否無望相信一個謂詞會奇蹟般地橫穿陣列?

回答

0

好了,找到了另一個解決方案....

NSPredicate* predicate = [NSPredicate predicateWithFormat:@"name contains[cd] %@", user]; 

作品,但解析不支持 「載」,按PFQuery文件:

 
The following types of predicates are supported: 
* Simple comparisons such as =, !=, , =, and BETWEEN with a key and a constant. 
* Containment predicates, such as 「x IN {1, 2, 3}」. 
* Key-existence predicates, such as 「x IN SELF」. 
* BEGINSWITH expressions. 
* Compound predicates with AND, OR, and NOT. 
* SubQueries with 「key IN %@」, subquery. 

The following types of predicates are NOT supported: 
* Aggregate operations, such as ANY, SOME, ALL, or NONE. 
* Regular expressions, such as LIKE, MATCHES, CONTAINS, or ENDSWITH. 
* Predicates comparing one key to another. 
* Complex predicates with many ORed clauses. 

有什麼建議?

+0

你試過用單個'='...'name =%@' –

+0

是的,它是一樣的。嘗試一種不同的方法,如果它有效,將會更新答案。 –

0

因此很明顯,解析需要不同的考慮到這種類型的問題,因爲這裏http://blog.parse.com/2013/03/19/implementing-scalable-search-on-a-nosql-backend/

描述所以在我的情況下,正確的方法是創建另一個表合作者,使它有「名」和「電子郵件」,並在原始表中保留對該表的引用數組。

但是由於我已經實現了大量的代碼,我做了一個解決方法 - 在同一張表上創建了一個附加的數組列,其中只有我想要的用戶名信息。這樣我就可以做查詢

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name IN {%@}", user]; 
     query = [PFQuery queryWithClassName:table predicate:predicate]; 

希望這可以幫助別人! :-D

乾杯!