开发者

NSDictionary Key For Value/Object? [duplicate]

开发者 https://www.devze.com 2023-03-08 01:17 出处:网络
This question already has answers here: How 开发者_StackOverflow社区to get the key for a given object from an NSMutableDictionary?
This question already has answers here: How 开发者_StackOverflow社区to get the key for a given object from an NSMutableDictionary? (4 answers) Closed 3 years ago.

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


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


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


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.

0

精彩评论

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