Parse NSDictionary to a string with custom separators

泪湿孤枕 提交于 2020-01-12 18:48:22

问题


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 = myemailaddress@is.short

becomes name=Fred&password=cakeismyfavoritefood&email=myemailaddress@is.short

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


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/3873714/parse-nsdictionary-to-a-string-with-custom-separators

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!