[英]How to filter an object array using another array to define which objects to filter out
在xcode中,我有一个数据库,可以从联机sql数据库中请求该数据库,并且可以将其存储到数组或NSDictionary或其他类型中。 另外,在应用程序中生成了一个数字数组,该数字数组对应于数据库的列之一。
我想过滤数据库以仅显示与生成的数组有关的对象。 过滤后,我想在字符串中列出结果。 如果需要,可以将在线服务器中的数据库存储在NSArray或NSDictionary中,以及其他我不知道的格式。
该过程如下所示:
数据库数组:生成的数组:过滤数据库后的结果数组:
ID | Name ID FilteredNames
|
1A | Hannah 1A Hannah
2A | John 1B Steve
3A | Peter 2B Zara
1B | Steve
2B | Zara
3B | Kyle
结果数组“ FilteredNames”转换为字符串列表,如下所示:
NamesString = @"Hannah, Steve, Zara"
然后,我计划将NamesString传递给标签,如下所示:
label.text=NamesString;
因此视图中的标签仅显示:
Hannah, Steve, Zara
我几乎需要整个过程的帮助。
编辑在马丁的评论之后,将谓词格式更改为一种更合适的谓词格式。
- (NSArray *)filterObjects:(NSArray *)objects withNames:(NSArray *)names {
return [objects filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"name IN %@", names]];
}
// given that the 'objects' array is what you get from server
NSArray *objects = @[
@{@"id" : @"1A", @"name" : @"Hannah"},
@{@"id" : @"2A", @"name" : @"John"},
@{@"id" : @"3A", @"name" : @"Peter"},
@{@"id" : @"1B", @"name" : @"Steve"},
@{@"id" : @"2B", @"name" : @"Zara"},
@{@"id" : @"3B", @"name" : @"Kyle"}
];
NSArray *filteredObjects = [self filterObjects:objects withNames:@[@"Hannah", @"John", @"Zara"]];
NSLog(@"filteredObjects: %@", filteredObjects); // prints them out as dictionaries
NSString *unitedNames = [[filteredObjects valueForKeyPath:@"@unionOfObjects.name"] componentsJoinedByString:@", "];
NSLog(@"unitedNames: %@", unitedNames); // comma separated array of names
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.