Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse NSDictionary to a string with custom separators

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?

like image 297
Emil Avatar asked Oct 06 '10 14:10

Emil


2 Answers

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]];
}
like image 177
Vladimir Avatar answered Nov 12 '22 09:11

Vladimir


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];
like image 38
Benoît Avatar answered Nov 12 '22 10:11

Benoît