如何创建一个试图在数组内的字典中查找对象的NSPredicate?
例如:
MyArray {
[0]: Dictionary {
email: test@test.com
name: John Smith
}
[1]: Dictionary {
email: other@test.com
name: Mary Davis
}
}
如何在“名称”字段中查看MyArray是否包含“Mary Davis”?
我试过
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 :(得分:0)
好的,找到了另一个解决方案......
NSPredicate* predicate = [NSPredicate predicateWithFormat:@"name contains[cd] %@", user];
有效,但根据PFQuery文档,Parse不支持“contains”:
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.
有什么建议吗?
答案 1 :(得分:0)
显然,Parse需要对此类问题采取不同的看法,如此处所述http://blog.parse.com/2013/03/19/implementing-scalable-search-on-a-nosql-backend/
因此,在我的情况下,正确的方法是创建另一个表Collaborator,其中包含“name”和“email”字段,并在原始表中保留对此表的引用数组。
然而,由于我已经实现了大量代码,我做了一个解决方法 - 在同一个表上创建了一个附加数组列,只包含我想要的用户名信息。通过这种方式,我能够进行查询
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name IN {%@}", user];
query = [PFQuery queryWithClassName:table predicate:predicate];
希望这有助于某人! :-D
干杯!