Jeremy P
Jeremy P

Reputation: 1407

NSDictionary get property within list of objects - Objective C

How would I get "Dog" from the following dictionary?

{
  Id = "123";
  Animal = [{
     Id = "456";
     Type = "Dog";
     Sound = "Bark";
  },
  {
     Id = "789";
     Type = "Cat";
     Sound = "Meow";
  }]
}

I tried

NSString *firstAnimalType = dictionary[@"Animal"][@"Type"];

However since there are multiple animals, it can't recognize what I am trying to find. How would I get the first animal out of the list so that I can access its type? Thanks!

Upvotes: 1

Views: 968

Answers (6)

Bhadresh Kathiriya
Bhadresh Kathiriya

Reputation: 3244

Try this code:

{
 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";
}

Upvotes: 0

Subramani
Subramani

Reputation: 477

Enumeration method will help and you can stop when and where you want

[myDict[@"Animal"] enumerateObjectsUsingBlock:^(id  _Nonnull objList, NSUInteger idx, BOOL * _Nonnull stop) {

       NSLog(@"%@",objList[@"Type"]);            
        *stop = YES; //You can stop where you want

}];

Upvotes: 1

Er. Khatri
Er. Khatri

Reputation: 1414

You can use some thing like this, first get animal object and if it exists then find its type from it

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"];
}

Upvotes: 1

Nirmalsinh Rathod
Nirmalsinh Rathod

Reputation: 5186

Here you go:

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.");
}

Upvotes: 0

szhukov
szhukov

Reputation: 26

for (NSDictionary *animal in dictionary[@"Animal"]) {
   NSString *type = animal[@"Type"];
   if ([type isKindOfClass:[NSString class]] && [type isEqualToString:@"Dog"]) {
    // Dog found
   }
}

Upvotes: 0

glyvox
glyvox

Reputation: 58049

You can simply access the first element of the array with castings and get its Type value.

NSString *firstAnimalType = ((NSDictionary *)[((NSArray *)dictionary[@"Animal"]) objectAtIndex: 0])[@"Type"];

Upvotes: 0

Related Questions