Search code examples
objective-cxcodensarraynsdictionary

Unable to get the key of a value from an NSDictionary in Xcode


I was trying to get the key of a value by using the value itself from an NSDictionary in my Xcode project. I am using the following dictionary:

_itemDictionary = @{
        @"Electronics" : @[@"DVD player", @"Laptop", @"PC", @"PS4", @"Radio", @"Speaker", @"TV"],
        @"Clothing" : @[@"Air jordan", @"Bracelet", @"Fila", @"Jeans", @"T-shirt", @"Todds", @"Tag Heuer"],
        @"Cleaning products" : @[@"Ajax", @"Ariel", @"Bounty", @"Clorox", @"Dettol", @"Tide", @"Vileda"],
        @"Baby products" : @[@"Baby bottle", @"Baby milk", @"Johnson's wipes", @"Pampers"]
    };

And I am trying to get the key of a value that is on a cell of a table view like below:

NSString *name = self.itemNames[indexPath.row];
        
cell.textLabel.text = name;
//get all keys for current item
NSArray *keys = [_itemDictionary allKeysForObject:name];
        
NSLog(@"%lu", (unsigned long)keys.count);

So what I realized is that the count of the keys NSarray I am using is always 0 whatever the name of the item is.

I tried to see the suggested solutions before posting this question here, but none helped me and that's why I posted it. It would mean so much if anyone would help! Thanks guys.


Solution

  • So with the hint given by John elemans, I realized that the dictionary actually contained arrays. And in order for me to check which arrays contained the name that I was looking for, I had to first get all the arrays in the dictionary and then go through each one of them and check which one contained the element. After that, I used the array that contained the element to get its corresponding key.

    Happy coding!