[英]how to get index of value in dictionary in array
像这样的数组:
<array> <dict> <key>Place</key> <string>A</string> <key>Name</key> <string>B</string> <key>Object</key> <string>C</string> </dict> <dict> <key>Place</key> <string>D</string> <key>Name</key> <string>E</string> <key>Object</key> <string>F</string> </dict> <dict> <key>Place</key> <string>X</string> <key>Name</key> <string>Y</string> <key>Object</key> <string>Z</string> </dict> <dict> <key>Place</key> <string>S</string> <key>Name</key> <string>T</string> <key>Object</key> <string>U</string> </dict> ... </array>
//由于某种原因,我通过删除原始的顶级数组简化了此示例的级别。 现在它们看起来像是由一些字典组成的数组。
例如,可以通过[[objectArray objectAtIndex:i] valueForKey:@"Place"]
获得任何值,例如X
然后,在另一个地方仍处于相同.m
, 只需要利用X到反转得到什么,其中X是字典的索引。 因为在这个地方,只能访问objectArray。
应该采取什么正确的方法?
再次使用KVC!
具有数组时的3行:D
NSArray *arrayWithDicts = @[d1,d2,d3,d4];//your array!
NSArray *arrayWithPlaces = [arrayWithDicts valueForKey:@"Place"];
NSUInteger index = [arrayWithPlaces indexOfObject:@"cologne"];
NSDictionary *dict = index != NSNotFound ? arrayWithDicts[index] : nil;
#import <Foundation/Foundation.h>
int main(int argc, char *argv[]) {
@autoreleasepool {
//build demo array
NSDictionary *d1 = @{@"Place": @"clackson"};
NSDictionary *d2 = @{@"Place": @"berlin"};
NSDictionary *d3 = @{@"Place": @"cologne"};
NSDictionary *d4 = @{@"Place": @"mclean"};
NSArray *arrayWithDicts = @[d1,d2,d3,d4];
//get all places
NSArray *arrayWithPlaces = [arrayWithDicts valueForKey:@"Place"];
assert(arrayWithDicts.count == arrayWithPlaces.count);
//find place and get dict
NSUInteger index = [arrayWithPlaces indexOfObject:@"cologne"];
NSDictionary *dict = index != NSNotFound ? arrayWithDicts[index] : nil;
NSLog(@"%@", dict);
}
}
您需要遍历外部数组,并且在该循环中需要遍历内部数组,查找@"Place"
值为X
的字典。 这是一种实现方法:
@implementation NSArray (StackOverflow)
- (NSIndexPath *)indexPathOfDictionaryWithPlace:(NSString *)place {
// I can't refer directly to an array inside a block, so I have to add an extra variable.
NSUInteger indexStorage[2];
NSUInteger *indexes = indexStorage;
indexes[0] = [self indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
NSArray *subarray = obj;
indexes[1] = [subarray indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
NSDictionary *dictionary = obj;
return [place isEqualToString:dictionary[@"Place"]];
}];
return indexes[1] != NSNotFound;
}];
if (indexes[0] == NSNotFound) {
return nil;
} else {
return [NSIndexPath indexPathWithIndexes:indexes length:2];
}
}
@end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.