NSDictionary Key For Value/Object?

2019-03-12 00:49发布

Can we get the key for an object in an NSDictionary by passing a particular value or object?

3条回答
地球回转人心会变
2楼-- · 2019-03-12 01:11

-[NSDictionary allKeysForObject:] returns an NSArray of all the keys whose objects match the passed object, where "match" is determined by isEqual:.

查看更多
倾城 Initia
3楼-- · 2019-03-12 01:26

This is how you can get a first key for object (in case it is an NSString):

NSArray *keys = [yourDic allKeysForObject:yourObject];
NSString *yourKey;
if ([keys count] > 0) {
   yourKey = keys[0];
}

This handles if the object is not found in in the dictionary.

查看更多
Ridiculous、
4楼-- · 2019-03-12 01:32

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 lastObject];

//"key" is now equal to the key of the object you were looking for
查看更多
登录 后发表回答