我如何从下面的字典中获得“狗”?
{
Id = "123";
Animal = [{
Id = "456";
Type = "Dog";
Sound = "Bark";
},
{
Id = "789";
Type = "Cat";
Sound = "Meow";
}]
}
我试过
NSString *firstAnimalType = dictionary[@"Animal"][@"Type"];
然而,由于有多只动物,它无法识别我想要找到的东西。如何将第一只动物从列表中取出以便我可以访问它的类型?谢谢!
答案 0 :(得分:1)
你可以使用这样的东西,首先得到动物对象,如果它存在,那么从中找到它的类型
NSDictionary *firstAnimal = [dictionary[@"Animal"] firstObject];
if(firstAnimal) //in case your firstAnimal is Empty or it may be nil then may create any unwanted issues in further code so just check it first.
{
NSString *firstAnimalType = firstAnimal[@"Type"];
}
答案 1 :(得分:1)
枚举方法将有所帮助,您可以随时随地停止
[myDict[@"Animal"] enumerateObjectsUsingBlock:^(id _Nonnull objList, NSUInteger idx, BOOL * _Nonnull stop) {
NSLog(@"%@",objList[@"Type"]);
*stop = YES; //You can stop where you want
}];
答案 2 :(得分:0)
您只需使用castings访问数组的第一个元素并获取其Type
值。
NSString *firstAnimalType = ((NSDictionary *)[((NSArray *)dictionary[@"Animal"]) objectAtIndex: 0])[@"Type"];
答案 3 :(得分:0)
for (NSDictionary *animal in dictionary[@"Animal"]) {
NSString *type = animal[@"Type"];
if ([type isKindOfClass:[NSString class]] && [type isEqualToString:@"Dog"]) {
// Dog found
}
}
答案 4 :(得分:0)
你走了:
NSArray *aryFinalAni = [dicMain valueForKey:@"Animal"];
NSArray *aryType = [aryFinalAni valueForKeyPath:@"Type"];
if([aryType containsObject:@"Dog"])
{
int indexOfDog = (int)[aryType indexOfObject:@"Dog"];
NSMutableDictionary *dicDog = [aryFinalAni objectAtIndex:indexOfDog];
NSLog(@"%@",dicDog);
}
else
{
NSLog(@"There is no Dog found.");
}
答案 5 :(得分:0)
试试这段代码:
{
Id = "123";
Animal = [{
Id = "456";
Type = "Dog";
Sound = "Bark";
},
{
Id = "789";
Type = "Cat";
Sound = "Meow";
}]
}
1> NSArray *items = dictionary["Animal"];
2>
NSPredicate *predicate1 = [NSPredicate predicateWithFormat: @"Type CONTAINS[cd] %@", "Dog"];
NSArray *arrData = [items filteredArrayUsingPredicate:predicate1];
if arrData.count > 0 {
dictionary = [arrData objectAtIndex:0];
}
Result:
{
Id = "456";
Type = "Dog";
Sound = "Bark";
}