开发者

NSLocalizedString - Format not a string literal and no format arguments (xcode)

I get the "format not a string..." message when doing the following:

NSString* string1 = [[NSString alloc] initWithFormat:NSLocalizedString(@"Update Now", @"Update开发者_C百科 Now Item")];
NSString* string2 = [[NSString alloc] initWithFormat:NSLocalizedString(@"Register", @"Register Now")];

It works fine i.e. the app doesn't crash on the device or simulator, and the localized text displays just fine also.

I'm trying to understand why is it then that I'm getting this particular error message. As far as I'm aware this is how you're meant to use localized strings in Objective C.


Simplest way to use localized string is:

NSString* myString = NSLocalizedString(@"Update Now",@"Update Now");

Now keep in mind myString is autoreleased - which you would generally need for a string.

In the examples you give your strings are retained (because you use initWithFormat). Guessing "update now" and such are going to be shown in the user UI, possibly trough a UILabel you don't need a retained string - when you do assign the string to a UILabel it will retain it automatically (as the text is stored in a retained property)


NSLocalizedString is a macro, which is actually;

[[NSBundle mainBundle] localizedStringForKey:(key) value:@"" table:nil]

So, why on earth do you need another NSString unless you do some post-processing like format replacing, it returns an NSString anyway!

you can retain it if you like...


You should not use initWithFormat: here at all because you are not dealing with a format string.

But if you use it, always use it like this:

[[NSString alloc] initWithFormat:@"%@", NSLocalizedString(@"Update Now", @"Update Now Item")];

Otherwise, the risk is that the result of NSLocalizedString contains a string format specifier (like %d or something), and that would crash your app.


The warning reported by the compiler is correct. The string returned from NSLocalizedString(@"Update Now", @"Update Now Item") is not a format string, because it does not have format specifier inside.

As Ican Zilb said in another answer, the best solution is to directly use:

NSString* myString = NSLocalizedString(@"Update Now",@"Update Now Item");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜