如何将值从NSMutableDictionary复制到Map

How do I copy values from NSMutableDictionary to a Map?

本文关键字:复制 Map NSMutableDictionary      更新时间:2023-10-16

我需要接受字符串的键值对的NSMutableDictionary,我需要复制到stl映射。有简单的方法吗?我试过了,但是行不通。

NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
    [dictionary setObject:@"10" forKey:@"6"];
    [dictionary setObject:@"10" forKey:@"7"];
    [dictionary setObject:@"10" forKey:@"8"];
    NSEnumerator *enumerator = [dictionary keyEnumerator];
    NSString *key;
    while ((key = [enumerator nextObject])) {
        std::string *keyString = new std::string([key UTF8String]);
        std::string *valueString = new std::string([[dictionary objectForKey:key] UTF8String]);
        map[*keyString] = *valueString;
    }

你为什么要使用new ?只需将-UTF8String的结果直接传递给地图,它就会为您将它们转换为std::string s:

map[[key UTF8String]] = [[dictionary objectForKey:key] UTF8String];

你现有的new代码不仅是无用的,但它也泄漏字符串。


你也应该抛弃NSEnumerator。多年来,我们有更好的方法来列举字典。具体来说,您可以使用快速枚举,也可以使用基于块的枚举。快速枚举循环如下所示:

for (NSString *key in dictionary) {
    map[[key UTF8String]] = [[dictionary objectForKey:key] UTF8String];
}

基于块的枚举看起来像这样:

// if map is a local variable it must be declared with __block
// like __block std::map<std::string,std::string> map;
// If it's static, global, or an instance or member variable, then it's fine as-is
[dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *value, BOOL *stop){
    map[[key UTF8String]] = [value UTF8String];
}];

在这种情况下,我会推荐快速枚举循环,因为它不需要修改map的声明。