我有一个带有一些值的NSMutableDictionary,我需要将键和值连接成一个字符串,所以
> name = Fred
> password = cakeismyfavoritefood
> email = myemailaddress@is.short
变为name=Fred&password=cakeismyfavoritefood&email=myemailaddress@is.short
我该怎么做?有没有办法将NSDictionaries
加入字符串?
答案 0 :(得分:14)
您可以轻松地枚举字典键和对象:
NSMutableString *resultString = [NSMutableString string];
for (NSString* key in [yourDictionary allKeys]){
if ([resultString length]>0)
[resultString appendString:@"&"];
[resultString appendFormat:@"%@=%@", key, [yourDict objectForKey:key]];
}
答案 1 :(得分:6)
与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];