2015-12-31 64 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; 
}