How can I change keys and values ​​in NSDictionary?

I want to know how to invert NSDictionary.

I saw some crazy code like

NSDictionary *dict = ...;
NSDictionary *swapped  = [NSDictionary dictionaryWithObjects:dict.allKeys forKeys:dict.allValues];

which according to the documentation is not secure at all, because the order allValuesand allKeyscan not be guaranteed.

+4
source share
2 answers
NSDictionary *dict = ...;    
NSMutableDictionary *swapped = [NSMutableDictionary new];
[dictionary enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) {
    swapped[value] = key;
}];

Please note that the values ​​must also comply with the protocol NSCopying.

+4
source

You are right, this code is crazy, but there are two ways to get an array of values ​​in the order given by the array of keys:

NSArray * keys = [dict allKeys];
NSArray * vals = [dict objectsForKeys:keys notFoundMarker:nil];

NSDictionary * inverseDict = [NSDictionary dictionaryWithObjects:keys
                                                         forKeys:vals];

or

NSUInteger count = [dict count];
id keys[count];
id vals[count];
[dict getObjects:vals andKeys:keys];

NSDictionary * inverseDict = [NSDictionary dictionaryWithObjects:keys
                                                         forKeys:vals
                                                           count:count];

, , . hfossli, , , NSCopying, .

+3

All Articles