2015-12-31 25 views
0

在我们当前的实现中,我们想要更改字符串参数(Push notification loc-args)并添加新参数。但我们希望我们旧版本的用户仍然使用参数#3,对于新用户,我们想要用户参数#4。因此,在我们新的实施,我们有以下代码:

NSString *format = @"%[email protected], %[email protected] ,%[email protected]"; 
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:

注意任何其他的选择:苹果锁屏推送通知是正确的(Argument 2, Argument 1 ,Argument 4),但不stringWithFormat:处理它的方式

+0

“旧版本”?什么?如果它是一个应用程序,那么旧版本如何看到这些变化? – trojanfoe

+0

其实参数是通过推送通知发送的,所以如果我们改变参数,'旧版本'的应用程序将获得更新的参数列表。只有格式在应用程序中。 –

+0

请参阅http://stackoverflow.com/questions/2944704/advanced-localization-with-omission-of-arguments-in-xcode:*“当使用编号参数说明时,指定第N个参数**需要**全部在格式字符串中指定了从第一个到第(N-1)个主要参数。“* - 如果在格式字符串中省略第三个参数,则行为未定义。 –

回答

0

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

/** 
@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\\[email protected]"; 

    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:@"[email protected]" 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; 
}