编译器警告不佳

时间:2014-01-27 12:43:46

标签: ios objective-c nsstring

如何摆脱XCode 5.1中的编译器警告

Stringtable中的

当然是一个带有格式说明符的字符串(已更新:现在位于代码前面)

"fmtDetail" = "Count: %d";

int number = 0;
//Compiler warning: Data argument not used by format string
NSString *text = [NSString stringWithFormat:NSLocalizedString(@"fmtDetail", nil), number];

//this gets no warning
NSString *fmtDetail = NSLocalizedString(@"fmtDetail", nil);
NSString *text2 = [NSString stringWithFormat:fmtDetail, number];

2 个答案:

答案 0 :(得分:2)

编译器警告不是很糟糕 - 你应该纠正你的代码。

%d中似乎缺少@"fmDetail"(或类似)。

或者你应该摆脱number论证 - 没有使用。

取决于你实际上要做的事情......

NSString *text = [NSString stringWithFormat:NSLocalizedString(@"fmtDetail%d", nil), number];

NSString *text = [NSString stringWithFormat:NSLocalizedString(@"fmtDetail %d", nil), number];

NSString *text = [NSString stringWithString:NSLocalizedString(@"fmtDetail", nil)];

第二个注释:此@"fmtDetail%d"应该匹配 plist字典中的key(已翻译的字符串)。它也可以是@"theDeatils“ - 从plist返回的字符串实际上应该保存字符串的格式化数据。

为什么要使用%d中的key?如果NSLocalizedString找不到包含相应密钥的字符串,则key会返回{{1}}。

编辑: MartinR找到了出现此警告的真正原因。只是一个可能有用的注释:因为本地化字符串通常意味着翻译成许多语言(duh),您可能需要使用numbered placeholders - 并非所有语言都共享相同的基本句子结构。

答案 1 :(得分:2)

这似乎不是一个错误,而是Xcode 5.1(beta)附带的编译器的新功能。现在预计在

[NSString stringWithFormat:NSLocalizedString(key, ...), arguments... ]

密钥本身是给定参数的有效格式。 (换句话说,密钥使用与字符串文件中的值相同的格式说明符)。 例如:

// Source code:
[NSString stringWithFormat:NSLocalizedString(@"Count = %d", nil), number]
// Localizable.strings:
"Count = %d" = "Die Anzahl ist %d";

这是优势,因为编译器现在可以检查数量和类型 格式说明符的格式与实际参数匹配,即使是可本地化的格式 字符串。这是不可能的(据我所知)。

例如,这会在Xcode 5.1 beta中引发警告,但在Xcode 5.0.2中不会发出警告:

[NSString stringWithFormat:NSLocalizedString(@"fmtDetail %f", nil), 13];
// warning: format specifies type 'double' but the argument has type 'int' [-Wformat]

(正如@rokjarc已经指出的那样,使用有效的格式字符串作为键 无论如何,因为如果没有匹配的字符串,NSLocalizedString()会返回密钥 可以在Localizable.strings文件中找到。)