views:

39

answers:

2

Hey!

I have an NSMutableDictionary with some values in it, and I need to join the keys and values into a string, so

> name = Fred
> password = cakeismyfavoritefood
> email = [email protected]

becomes name=Fred&password=cakeismyfavoritefood&[email protected]

How can I do this? Is there a way to join NSDictionaries into strings?

+1  A: 

You can easily do that enumerating dictionary keys and objects:

NSMutableString *resultString = [NSMutableString string];
for (NSString* key in [yourDictionary allKeys]){
    if ([resultString length]>0)
       [resultString appendString:@"&"];
    [resultString appendFormat:@"%@=%@", key, [yourDict objectForKey:key]];
}
Vladimir
That's brilliant, thank you. :)
Emil
+1  A: 

Quite same question as Turning a NSDictionary into a string using blocks?

NSMutableArray* parametersArray = [[NSMutableArray alloc] init];
[yourDictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
    [parametersArray addObject:[NSString stringWithFormat:@"%@=%@", key, obj]];
}];
NSString* parameterString = [parametersArray componentsJoinedByString:@"&"];
[parametersArray release];
Benoît
Thanks, I didn't find that question before. (*Maybe because I asked first? :)*) I don't quite see the reason to use `alloc-init-**autorelease**` here, though. `autorelease` should only be used if it is really necessary, as it is NOT in this example (simply release the array after setting the (`NSString`).
Emil
Emil
Benoît