How to get the key for a given object from NSMutableDictionary?

I have an object that is in a large NSMutableDictionary, and you need to figure out which key it has. Therefore, I want to see what the β€œtable” is from both columns. Not only with keys, but also with objects (to get keys). Is it possible?

+29
iphone nsmutabledictionary
May 7 '10 at 10:02
source share
4 answers

Look at the parent class (NSDictionary)

- (NSArray *)allKeysForObject:(id)anObject 

which will return an NSArray of all keys for a given Object value. BUT it does this by sending an isEqual message to each dictionary object, so for your large dataset this may not be the best way.

Perhaps you need to preserve some additional structure of the indexing structure so that you can find objects at some critical values ​​inside them associated with the key without directly comparing the objects.

+67
May 7, '10 at 10:20
source share

To answer the question more specifically, use the following to get the key for a specific 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 
+19
May 01 '12 at 20:23
source share

Take a look at:

 - (NSArray *)allKeysForObject:(id)anObject 
+6
May 7, '10 at 10:19
source share

This is definitely possible with the NSDictionary block method.

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

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

Use it as follows:

  NSSet *keys = [myDictionary keysOfEntriesPassingTest:^BOOL(id key, id obj, BOOL *stop) { BOOL found = (objectForWhichIWantTheKey == obj); if (found) *stop = YES; return found; }]; 

Check this answer for more details.

How to specify a block object / predicate required by NSDictionaryAfEntriesPassingTest keys?

+6
Sep 26 '12 at 14:14
source share



All Articles