开发者

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

开发者 https://www.devze.com 2022-12-29 18:21 出处:网络
I have an object which is in an big NSMutableDic开发者_开发百科tionary, 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 wit

I have an object which is in an big NSMutableDic开发者_开发百科tionary, 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?


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


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?

0

精彩评论

暂无评论...
验证码 换一张
取 消