将NSDictionary解析为具有自定义分隔符的字符串

时间:2010-10-06 14:43:36

标签: iphone join nsstring nsdictionary separator

我有一个带有一些值的NSMutableDictionary,我需要将键和值连接成一个字符串,所以

> name = Fred
> password = cakeismyfavoritefood
> email = myemailaddress@is.short

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

我该怎么做?有没有办法将NSDictionaries加入字符串?

2 个答案:

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