开发者

Turning a NSDictionary into a string using blocks?

开发者 https://www.devze.com 2023-01-19 09:33 出处:网络
I\'m sure there is a way to do this using blocks, but I cant figure it out. I want to to turn an NSDictionary into url-style string of parameters.

I'm sure there is a way to do this using blocks, but I cant figure it out. I want to to turn an NSDictionary into url-style string of parameters. If I have an NSDictionary which looks like this:

dict = [NSDictionary dictionaryWithObjectsAndKeys:@"blue", @"color", @"large", @"size", nil]];

Then how would I turn that into a string that looks like this:

"color=blue&size=large"

EDIT

Thanks for the clues below. This should do it:

NSMutableString *parameterString;
[dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop开发者_运维知识库) {
    [parameterString appendFormat:@"%@=%@&", key, obj];
}];
parameterString = [parameterString substringToIndex:[string length] - 1];


Quite same solution but without the substring:

NSMutableArray* parametersArray = [[[NSMutableArray alloc] init] autorelease];
[dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
    [parametersArray addObject:[NSString stringWithFormat:@"%@=%@", key, obj]];
}];
NSString* parameterString = [parametersArray componentsJoinedByString:@"&"];


Create a mutable string, then iterate the dictionary getting each key. Look up the value for that key, and add the key=value& to the string. When you finish that loop, remove the last &.

I presume this is going to be fed through a URL, you will also want to have some method that encodes your strings, in case they contain items like & or +, etc.


NSMutableString* yourString = @"";

for (id key in dict) {
     [yourString appendFormat:@"%@=%@&", key, ((NSString*)[dict objectForKey:key])];
}

NSRange r;
r.location = 0;
r.size = [yourString length]-1;
[yourString deleteCharactersInRange:r];
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号