Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Creating a query string from an NSDictionary.
NSDictionary *queryParameters = [NSDictionary dictionaryWithValuesAndKeys:1, @"page", nil, @"enabled", 25, @"size", nil];
[queryParameters queryString]; // This will return "?page=1&enabled&size=25"
#import <Foundation/Foundation.h>
@interface NSDictionary (QueryStringBuilder)
- (NSString *)queryString;
#import "NSDictionary+QueryStringBuilder.h"
static NSString * escapeString(NSString *unencodedString)
NSString *s = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
(CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ",
return [s autorelease];
@implementation NSDictionary (QueryStringBuilder)
- (NSString *)queryString
NSMutableString *queryString = nil;
NSArray *keys = [self allKeys];
if ([keys count] > 0) {
for (id key in keys) {
id value = [self objectForKey:key];
if (nil == queryString) {
queryString = [[[NSMutableString alloc] init] autorelease];
[queryString appendFormat:@"?"];
} else {
[queryString appendFormat:@"&"];
if (nil != key && nil != value) {
[queryString appendFormat:@"%@=%@", escapeString(key), escapeString(value)];
} else if (nil != key) {
[queryString appendFormat:@"%@", escapeString(key)];
return queryString;

The argument name for escapeString() should be unencodedString instead of string, as this is the name used on the CFURLCreateStringByAddingPercentEscapes call. My fork of this gist fixes this so the code compiles.

It also makes escapeString() a static function to avoid compiler warnings.


mramsden commented Oct 13, 2011

Thanks for the spots :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment