优雅地替换 URL / NSString 中的多个标记

发布于 2024-12-25 12:34:45 字数 872 浏览 3 评论 0原文

当我与后端通信时,我经常有这样的 URL:

http://myserver.com/api/endpoint?param1={PARAM1}&param2={PARAM2}

因此,在发出请求之前,我需要用实际值替换这些参数。因此,像下面这样的代码片段遍布我的代码:

myString = [[[uriString  stringByReplacingOccurrencesOfString:@"{PARAM1}" withString:@"..."]
              stringByReplacingOccurrencesOfString:@"{PARAM2}" withString:@"..."]
             stringByReplacingOccurrencesOfString:@"{PARAMn}" withString:@"..."];

我现在正在寻找一种优雅的方法来替换这些参数,我可以想到一些选项:

  1. 创建 NSString 类别:

    [myString ReplaceOccurencesOfStrings:@"{PARAM1}",@"{PARAM2}",nil withStrings @"value1",@"value2",nil];
    
  2. 创建一个与上面示例相同的 Util,只是我将字符串传递给它

  3. 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:

  1. Make a category of NSString:

    [myString replaceOccurencesOfStrings:@"{PARAM1}",@"{PARAM2}",nil withStrings @"value1",@"value2",nil];
    
  2. Make a Util which works the same as the above example, only that I pass it the string

  3. Same approach as 1. and 2. but using a NSDictionary with key value like this: 'PARAM1' -> 'value1' ...

What is the most efficient and elegant way to achieve this

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

迷途知返 2025-01-01 12:34:45

尝试使用[NSString stringWithFormat]

myString = [NSString stringWithFormat:@"http://myserver.com/api/endpoint?param1=%@¶m2=%@", @"valueOfParam1", @"valueOfParam2"];

Try to use [NSString stringWithFormat]:

myString = [NSString stringWithFormat:@"http://myserver.com/api/endpoint?param1=%@¶m2=%@", @"valueOfParam1", @"valueOfParam2"];
忘东忘西忘不掉你 2025-01-01 12:34:45

我曾经有一个项目,我向 NSString 添加了一个类别,它执行以下操作:

@implementation NSString (Interpolate)

#define COPYREGION(_endp)                                               \
    do                                                                  \
    {                                                                   \
        NSUInteger _pointer = _endp;                                    \
        NSRange _range = NSMakeRange(lastPoint, _pointer - lastPoint);  \
        NSString* _region = [self substringWithRange: _range];          \
        [buffer appendString: _region];                                 \
    }                                                                   \
    while (0)

- (void) appendTo: (NSMutableString*) buffer byInterpolating: (NSDictionary*) variables
{
    NSUInteger length = [self length];
    NSUInteger p = 0;
    NSUInteger lastPoint = 0;

    while (p < length)
    {
        unichar ch = [self characterAtIndex: p];
        if (ch != '

替换变量的语法是 $name$。出现 $$ 将成为单个美元字符。用法是:

NSDictionary* subst = [NSDictionary dictionaryWithObjectsAndKeys: @"param1", @"p1", @"param2", @"p2", nil];
return [@"Some template param1=$p1$, param2=$p1$" stringByInterpolating: subst];
) ++p; else { COPYREGION(p); NSUInteger start = ++p; while (p < length && [self characterAtIndex: p] != '

替换变量的语法是 $name$。出现 $$ 将成为单个美元字符。用法是:


) ++p;

            if (p == length) NSLog(@"Warning: missing closing '

替换变量的语法是 $name$。出现 $$ 将成为单个美元字符。用法是:


 in substitution marker");
            if (p == start + 1) [buffer appendString: @"$"];
            else
            {
                NSRange range = NSMakeRange(start, p - start);
                NSString* name = [self substringWithRange: range];
                NSString* value = [variables objectForKey: name];
                if (value) [buffer appendString: value];
            }
            lastPoint = ++p;
        }
    }

    COPYREGION(length);
}

- (NSString*) stringByInterpolating: (NSDictionary*) variables
{
    NSAutoreleasePool* pool = [NSAutoreleasePool new];
    NSMutableString* buffer = [NSMutableString string];

    [self appendTo: buffer byInterpolating: variables];

    NSString* answer = [buffer copy];
    [pool release];
    return [answer autorelease];
}

@end

替换变量的语法是 $name$。出现 $$ 将成为单个美元字符。用法是:

I had once a project where I added a category to NSString which does something like this:

@implementation NSString (Interpolate)

#define COPYREGION(_endp)                                               \
    do                                                                  \
    {                                                                   \
        NSUInteger _pointer = _endp;                                    \
        NSRange _range = NSMakeRange(lastPoint, _pointer - lastPoint);  \
        NSString* _region = [self substringWithRange: _range];          \
        [buffer appendString: _region];                                 \
    }                                                                   \
    while (0)

- (void) appendTo: (NSMutableString*) buffer byInterpolating: (NSDictionary*) variables
{
    NSUInteger length = [self length];
    NSUInteger p = 0;
    NSUInteger lastPoint = 0;

    while (p < length)
    {
        unichar ch = [self characterAtIndex: p];
        if (ch != '

The syntax for substitution variables is $name$. An occurrence of $$ becomes a single dollar character. Usage would be:

NSDictionary* subst = [NSDictionary dictionaryWithObjectsAndKeys: @"param1", @"p1", @"param2", @"p2", nil];
return [@"Some template param1=$p1$, param2=$p1$" stringByInterpolating: subst];
) ++p; else { COPYREGION(p); NSUInteger start = ++p; while (p < length && [self characterAtIndex: p] != '

The syntax for substitution variables is $name$. An occurrence of $$ becomes a single dollar character. Usage would be:


) ++p;

            if (p == length) NSLog(@"Warning: missing closing '

The syntax for substitution variables is $name$. An occurrence of $$ becomes a single dollar character. Usage would be:


 in substitution marker");
            if (p == start + 1) [buffer appendString: @"$"];
            else
            {
                NSRange range = NSMakeRange(start, p - start);
                NSString* name = [self substringWithRange: range];
                NSString* value = [variables objectForKey: name];
                if (value) [buffer appendString: value];
            }
            lastPoint = ++p;
        }
    }

    COPYREGION(length);
}

- (NSString*) stringByInterpolating: (NSDictionary*) variables
{
    NSAutoreleasePool* pool = [NSAutoreleasePool new];
    NSMutableString* buffer = [NSMutableString string];

    [self appendTo: buffer byInterpolating: variables];

    NSString* answer = [buffer copy];
    [pool release];
    return [answer autorelease];
}

@end

The syntax for substitution variables is $name$. An occurrence of $$ becomes a single dollar character. Usage would be:

落日海湾 2025-01-01 12:34:45

如果您只能使用格式,为什么要替换令牌,例如使用 stringByAppendingFormat

该函数的接口为:

-(NSString*) createRequestToURL:(NSString*) url_string withParams:(NSDictionary*) params {
//TODO:
}

其中字典中的键是参数名称。

Why replace tokens if you can just use the format, for example using stringByAppendingFormat.

The interface for the function would be:

-(NSString*) createRequestToURL:(NSString*) url_string withParams:(NSDictionary*) params {
//TODO:
}

Where key in the dictionary is param name.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文