7

I'm using NSLocalizedString in a particular message that works fine if the second parameter is passed as a variable, but fails with Use of undeclared identifier 'NSLocalizedString' and Too many arguments provided to function-like macro invocation if the second parameter is written exactly the same as the variable was set. I have working code using the variable, which is fine, I just want to understand the reasons for the failure to know how to avoid it in other situations.

With the following declarations:

NSString *branchTitle = [branchDictionary objectForKey:@"Title"];
NSString *localString = [NSMutableString stringWithFormat:@"%@ node title", branchTitle];

This works fine with no errors:

[navItem setTitle:NSLocalizedString(branchTitle, localString)];

... but this, which seems identical to me, fails with the errors noted above:

[navItem setTitle:NSLocalizedString(branchTitle, [NSMutableString stringWithFormat:@"%@ node title", branchTitle])];

Searching here and elsewhere I haven't found an explanation. I read through a number of hits on each error message and various NSLocalizedString issues, but nothing that tied them together. What I found about the second error message implied maybe an issue with clang and the number of commas in the statement, indicating that even though the extra comma is within the NSMutableString message, it was still being seen as an extra parameter by NSLocalizedString. Does that make any sense?

Not important for the question, but the statement is intended to set the localized version of a navigation bar title based on the English version pulled from a dictionary, which varies for different views. The NSMutableString portion defines the comment for the localization based on the English title.

EDIT: After resolving this issue per the accepted answer, below, I noticed another related issue. The declaration of localString was producing an "Unused variable" compiler warning, though it was clearly being used. This is also due to it being within a C-macro and for completeness, I'm adding a link to a relevant post here about suppressing that warning: How can I get rid of an “unused variable” warning in Xcode

4

1 回答 1

14

我相信这是糟糕的 C 宏扩展的结果。事实上,如果你写:

NSLocalizedString(branchTitle, ([NSString stringWithFormat:@"%@ node title", branchTitle]));

这将编译。由于某种原因,预处理器不能很好地处理其中的文本[](可能是因为它不知道 Objective-C 调用)并将其中的所有元素[]视为单独的参数:

#define NSLocalizedString(key, comment) \
    [[NSBundle mainBundle] localizedStringForKey:(key) value:@"" table:nil]

PS:当我写了糟糕的 C 宏扩展时,我的意思

宏扩展是一个棘手的操作,充满了令人讨厌的极端情况和情况,这些情况会使您认为优化预处理器扩展算法的方式非常微妙,但这种方式非常微妙。

于 2013-01-17T17:36:16.977 回答