将url params拆分并转换为字符串值的最佳方法

时间:2010-01-22 18:50:14

标签: iphone objective-c

我想将iPhone中打开app的自定义网址拆分为值,我的方案如下:

appname://user=jonsmith&message=blah%20blah

我希望能够将“用户”和“消息”作为两个NSStrings。关于最佳方法的任何建议?

3 个答案:

答案 0 :(得分:6)

假设您的网址位于名为NSURL的{​​{1}}对象中:

url

答案 1 :(得分:1)

使用Google的gtm_dictionaryWithHttpArgumentsString NSDictionary类别

http://code.google.com/p/google-toolbox-for-mac/source/browse/trunk/Foundation/GTMNSDictionary%2BURLArguments.h

答案 2 :(得分:-1)

NSString* yourString = @"appname://user=jonsmith&message=blah%20blah";
NSString* queryString = [yourString substringFromIndex:strlen("appname://")];
NSArray* queryArray = [queryString componentsSeparatedByString:@"&"];
NSMutableDictionary* queryDict = [NSMutableDictionary dictionary];
for (NSString* query in queryArray) {
    NSUInteger indexOfEqualsSign = [query rangeOfString:@"="].location;
    if (indexOfEqualsSign != NSNotFound) {
       NSString* key = [[query substringToIndex:indexOfEqualsSign] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
       NSString* value = [[query substringFromIndex:indexOfEqualsSign+1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
       [queryDict setObject:value forKey:key];
    }
}
return queryDict;

如果您需要节省更多内存,请使用NSScanner