unj2
unj2

Reputation: 53491

How do I copy values from NSMutableDictionary to a Map?

I need to accept NSMutableDictionary of key value pairs of strings and I need to copy to a stl map. Is there an easy way to do so? I tried this, but this doesn't work.

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;
    }

Upvotes: 2

Views: 2412

Answers (1)

Lily Ballard
Lily Ballard

Reputation: 185681

Why are you using new at all? Just pass the results of -UTF8String directly to the map, and it will turn them into std::strings for you:

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

Your existing new code is not only useless, but it's also leaking the strings.


You should also ditch the NSEnumerator. We've had better ways to enumerate a dictionary for a number of years now. Specifically, you could use fast enumeration, or you could use block-based enumeration. The fast enumeration loop looks like:

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

The block-based enumeration will look like this:

// 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];
}];

In this case I would recommend the fast-enumeration loop because it doesn't require modifying the declaration of map.

Upvotes: 5

Related Questions