【问题标题】:Multiple arguments in stringWithFormat: “n$” positional specifiersstringWithFormat 中的多个参数:“n$”位置说明符
【发布时间】:2015-12-31 12:09:52
【问题描述】:

在我们当前的实现中,我们希望更改字符串参数(推送通知 loc-args)并添加新参数。但是我们希望旧版本的用户仍然使用参数 #3,而对于新用户,我们希望用户参数 #4。所以在我们的新实现中,我们有以下代码:

NSString *format = @"%2$@,  %1$@  ,%4$@";
NSArray *arg = @[@"Argument 1", @"Argument 2",@"Argument 3",@"Argument 4"];
NSString *ouptput = [NSString stringWithFormat:format, arg[0], arg[1], arg[2], arg[3]];

输出:参数 2、参数 1、参数 3

我们期待它是

参数 2,参数 1,参数 4

我们如何才能实现Argument 4 到位。 stringWithFormat:的任何其他替代品

注意:Apple 锁屏推送通知是正确的 (Argument 2, Argument 1 ,Argument 4) 但stringWithFormat: 不是这样处理的

【问题讨论】:

  • “旧版本”?什么?如果它是一个应用程序,那么旧版本怎么会看到变化?
  • 实际上参数是通过推送通知发送的,所以如果我们更改参数,“旧版本”应用程序将获得更新的参数列表。应用程序中只有格式。
  • 参见stackoverflow.com/questions/2944704/…: "当使用编号参数规范时,指定第 N 个参数要求所有前导参数,从第一个到 (N- 1)th,在格式字符串中指定。" – 如果省略格式字符串中的第三个参数,则行为未定义。
  • @MartinR 你是对的。但苹果处理它。在呈现推送通知时,对于上述格式和参数,它将在锁定屏幕上显示为Argument 2, Argument 1 ,Argument 4。我也想在应用程序中实现同样的目标
  • 这是另一种解决方法:stackoverflow.com/questions/2946649/….

标签: ios objective-c stringwithformat


【解决方案1】:

我实现了一个自定义方法来实现预期的输出。此方法可以处理缺少的位置说明符。此方法仅适用于包含位置说明符%n$@ 的格式。

/**
 @param format String format with positional specifier
 @param arg Array of arguments to replace positional specifier in format
 @return Formatted output string
 */
+(NSString*)stringWithPositionalSpecifierFormat:(NSString*)format arguments:(NSArray*)arg
{
    static NSString *pattern = @"%\\d\\$@";

    NSError *error;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:&error];

    NSMutableString *mString = [[NSMutableString alloc] initWithString:format];
    NSArray *allMatches = [regex matchesInString:format options:0 range:NSMakeRange(0, [format length])];
    if (!error && allMatches>0)
    {
        for (NSTextCheckingResult *aMatch in allMatches)
        {
            NSRange matchRange = [aMatch range];
            NSString *argPlaceholder = [format substringWithRange:matchRange];
            NSMutableString *position = [argPlaceholder mutableCopy];
            [position replaceOccurrencesOfString:@"%" withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [position length])];
            [position replaceOccurrencesOfString:@"$@" withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [position length])];
            int index = position.intValue;
            //Replace with argument
            [mString replaceOccurrencesOfString:argPlaceholder withString:arg[index-1] options:NSCaseInsensitiveSearch range:NSMakeRange(0, [mString length])];
        }
    }
    return mString;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-16
    • 2020-05-08
    • 1970-01-01
    • 1970-01-01
    • 2016-07-30
    • 1970-01-01
    相关资源
    最近更新 更多