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(与上述相同)这是另一种反转字典的方法.对我来说最简单.
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)
| 归档时间: |
|
| 查看次数: |
3006 次 |
| 最近记录: |