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

丶灬走出姿态 提交于 2019-12-18 12:05:56

问题


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?


回答1:


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




回答2:


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



回答3:


Take a look at:

- (NSArray *)allKeysForObject:(id)anObject



回答4:


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?



来源:https://stackoverflow.com/questions/2787688/how-to-get-the-key-for-a-given-object-from-an-nsmutabledictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!