如何交换`NSMutableDictionary`键和值?

Kun*_*ani 9 iphone nsmutabledictionary ios

我有一个NSMutableDictionary,我想交换值和键.即,交换后的值变为键,其对应的键变为值所有键和值都是唯一的.寻找一个适当的解决方案,因为尺寸非常大.此外,键和值是NSString对象

Gab*_*lla 16

NSMutableDictionary *d = [NSMutableDictionary dictionaryWithDictionary:@{
                             @"key1" : @"value1",
                             @"key2" : @"value2"}];

for (NSString *key in [d allKeys]) {
    d[d[key]] = key;
    [d removeObjectForKey:key];
}

NSLog(@"%@", d); // => { value1 : key1,
                 //      value2 : key2 }
Run Code Online (Sandbox Code Playgroud)

假设

  • 唯一值(因为它们将成为键)
  • 值符合NSCopying(与上述相同)
  • 没有值等于任何键(否则在此过程中会丢失冲突的名称)

  • 枚举的集合是`[d allKeys]`,在枚举期间*不*变异. (11认同)

Tri*_*ops 5

这是另一种反转字典的方法.对我来说最简单.

NSArray *keys = dictionary.allKeys;
NSArray *values = [dictionary objectsForKeys:keys notFoundMarker:[NSNull null]];
[dictionary removeAllObjects]; // In case of huge data sets release the contents.
NSDictionary *invertedDictionary = [NSDictionary dictionaryWithObjects:keys forKeys:values];
[dictionary setDictionary:invertedDictionary]; // In case you want to use the original dictionary.
Run Code Online (Sandbox Code Playgroud)

  • @GabrielePetronella对不起.但是如果你有性能或内存问题,也许你可以使用`-allKeysForObject:`进行反向查找.没有分配,没有复制. (2认同)