[英]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.