Ios 获取数组中具有特定键的NSDictionary
我有一大堆字典 字典有这样的键:颜色、数字、代码、描述和大小 现在我有一个键,我想在数组中找到字典,一些神奇的命令,如:Ios 获取数组中具有特定键的NSDictionary,ios,iphone,cocoa-touch,nsarray,nsdictionary,Ios,Iphone,Cocoa Touch,Nsarray,Nsdictionary,我有一大堆字典 字典有这样的键:颜色、数字、代码、描述和大小 现在我有一个键,我想在数组中找到字典,一些神奇的命令,如: NSDictionary *oneDict = [get a dictionary from myArray where "code" is equal to "32"]; 代码是一个键,32是一个值 我知道如何枚举数组并在每个dict中逐个搜索,但我知道objective-c是一个充满技巧的包,可能存在一个神奇的命令,可以通过外科手术从数组中一行提取此字典 有什么线索吗?
NSDictionary *oneDict = [get a dictionary from myArray where "code" is equal to "32"];
代码是一个键,32是一个值
我知道如何枚举数组并在每个dict中逐个搜索,但我知道objective-c是一个充满技巧的包,可能存在一个神奇的命令,可以通过外科手术从数组中一行提取此字典
有什么线索吗?如果您打算多次查找,并且不介意花一些时间进行设置,您可以创建一个字典,将代码的值映射到包含这些值的字典。i、 e:
NSDictionary * mapping = [ NSDictionary dictionaryWithObjects:myArray forKeys:[ myArray valueForKey:@"code" ] ]
id answer = mapping[@"32" ] ;
这仅在代码包含唯一值时有效。如果值不是唯一的:
NSArray * codeValues = [ myArray valueForKey:@"code" ] ;
NSIndexSet indexes = [ codeValues indexesOfObjectsPassingTest:^BOOL(id object){ [ object isEqual:@"32" ] } ] ;
NSArray * matchingDictionaries = [ myArray objectsAtIndexes:indexes ] ;
matchingDictionaries将是一个数组,其中包含代码为@32的字典
将这些示例中的@32替换为您希望查找的代码值,&c.如果您打算多次查找,并且不介意花费一些时间进行设置,您可以创建一个字典,将代码值映射到包含这些值的字典。i、 e:
NSDictionary * mapping = [ NSDictionary dictionaryWithObjects:myArray forKeys:[ myArray valueForKey:@"code" ] ]
id answer = mapping[@"32" ] ;
这仅在代码包含唯一值时有效。如果值不是唯一的:
NSArray * codeValues = [ myArray valueForKey:@"code" ] ;
NSIndexSet indexes = [ codeValues indexesOfObjectsPassingTest:^BOOL(id object){ [ object isEqual:@"32" ] } ] ;
NSArray * matchingDictionaries = [ myArray objectsAtIndexes:indexes ] ;
matchingDictionaries将是一个数组,其中包含代码为@32的字典
将这些示例中的@32替换为您希望查找的代码值,&c。您可以使用indexOfObjectPassingTest获取对象索引:
NSUInteger index = [myArray indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
NSDictionary* dict = obj;
return [obj[@"code"] intValue] == 32;
}];
如果未找到,则结果将为NSNotFound 您可以使用indexOfObjectPassingTest获取对象索引:
NSUInteger index = [myArray indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
NSDictionary* dict = obj;
return [obj[@"code"] intValue] == 32;
}];
如果未找到,则结果将为NSNotFound 这可以通过NSPredicate更简单的工具来完成:
NSPredicate * predicate = [NSPredicate predicateWithFormat:@"code MATCHES[cd] %@", value];
NSArray *result = [myArray filteredArrayUsingPredicate:predicate];
结果数组将保存与该值匹配的所有NSDictionary。
看一看NSPredicate
它的功能非常强大这可以通过更简单的NSPredicate来实现:
NSPredicate * predicate = [NSPredicate predicateWithFormat:@"code MATCHES[cd] %@", value];
NSArray *result = [myArray filteredArrayUsingPredicate:predicate];
结果数组将保存与该值匹配的所有NSDictionary。
看一看NSPredicate
它非常强大