How to get the key for a given object from an NSMutableDictionary?
Asked Answered
S

4

33

I have an object which is in an big NSMutableDictionary, and need to find out which key this has. So I want to look up that "table" from both columns. Not only with keys, but also with objects (to get keys). Is that possible?

Sunup answered 7/5, 2010 at 10:2 Comment(0)
R
70

Look to the parent class (NSDictionary)

- (NSArray *)allKeysForObject:(id)anObject

Which will return a NSArray of all the keys for a given Object Value. BUT it does this by sending an isEqual message to each object of the Dictionary so for your large dataset this may not be best performance.

Maybe you need to hold some form of additional indexing structure structure(s) to allow you to locate the objects on some critical values within them, linked to the key without direct object comparison

Reitz answered 7/5, 2010 at 10:20 Comment(0)
C
19

To answer you question in a more specific manner, use the following to get a key for a particular object:

NSString *knownObject = @"the object";
NSArray *temp = [dict allKeysForObject:knownObject];
NSString *key = [temp objectAtIndex:0];

//"key" is now equal to the key of the object you were looking for
Countermeasure answered 1/5, 2012 at 20:23 Comment(0)
L
6

Take a look at:

- (NSArray *)allKeysForObject:(id)anObject
Lepton answered 7/5, 2010 at 10:19 Comment(0)
J
6

That is definitely possible with NSDictionary's block method

- (NSSet *)keysOfEntriesPassingTest:(BOOL (^)(id key, id obj, BOOL *stop))predicate;

You need to return objects which satisfy some condition (predicate).

Use it like this:

    NSSet *keys = [myDictionary keysOfEntriesPassingTest:^BOOL(id key, id obj, BOOL *stop) {

       BOOL found = (objectForWhichIWantTheKey == obj);
       if (found) *stop = YES;
       return found;

    }];

Check out this answer for more details

How do I specify the block object / predicate required by NSDictionary's keysOfEntriesPassingTest?

Jimmie answered 26/9, 2012 at 14:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.