优雅地替换 URL / NSString 中的多个标记
当我与后端通信时,我经常有这样的 URL:
http://myserver.com/api/endpoint?param1={PARAM1}¶m2={PARAM2}
因此,在发出请求之前,我需要用实际值替换这些参数。因此,像下面这样的代码片段遍布我的代码:
myString = [[[uriString stringByReplacingOccurrencesOfString:@"{PARAM1}" withString:@"..."]
stringByReplacingOccurrencesOfString:@"{PARAM2}" withString:@"..."]
stringByReplacingOccurrencesOfString:@"{PARAMn}" withString:@"..."];
我现在正在寻找一种优雅的方法来替换这些参数,我可以想到一些选项:
创建 NSString 类别:
[myString ReplaceOccurencesOfStrings:@"{PARAM1}",@"{PARAM2}",nil withStrings @"value1",@"value2",nil];
创建一个与上面示例相同的 Util,只是我将字符串传递给它
与
1.
和2.
的方法相同,但使用具有如下键值的 NSDictionary:'PARAM1' -> 'value1' ...
实现此目的最有效、最优雅的方法是什么
When I am communicating with my backend I often have URL like this:
http://myserver.com/api/endpoint?param1={PARAM1}¶m2={PARAM2}
So before issuing a request I need to substitute those params with actual values. So code fragments like the following are all over my code:
myString = [[[uriString stringByReplacingOccurrencesOfString:@"{PARAM1}" withString:@"..."]
stringByReplacingOccurrencesOfString:@"{PARAM2}" withString:@"..."]
stringByReplacingOccurrencesOfString:@"{PARAMn}" withString:@"..."];
I am now looking for an elegant way to substitute those params and I can think of a few options:
Make a category of NSString:
[myString replaceOccurencesOfStrings:@"{PARAM1}",@"{PARAM2}",nil withStrings @"value1",@"value2",nil];
Make a Util which works the same as the above example, only that I pass it the string
Same approach as
1.
and2.
but using a NSDictionary with key value like this:'PARAM1' -> 'value1' ...
What is the most efficient and elegant way to achieve this
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试使用
[NSString stringWithFormat]
:Try to use
[NSString stringWithFormat]
:我曾经有一个项目,我向
NSString
添加了一个类别,它执行以下操作:替换变量的语法是
$name$
。出现$$
将成为单个美元字符。用法是:I had once a project where I added a category to
NSString
which does something like this:The syntax for substitution variables is
$name$
. An occurrence of$$
becomes a single dollar character. Usage would be:如果您只能使用格式,为什么要替换令牌,例如使用 stringByAppendingFormat。
该函数的接口为:
其中字典中的键是参数名称。
Why replace tokens if you can just use the format, for example using stringByAppendingFormat.
The interface for the function would be:
Where key in the dictionary is param name.