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

若如初见. 提交于 2019-12-03 04:19:21

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

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

Take a look at:

- (NSArray *)allKeysForObject:(id)anObject
valdyr

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?

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