PDA

View Full Version : [Resolved] Concisely insert variables in localized string?




ArtOfWarfare
May 5, 2012, 10:30 PM
I currently have some rather long obj-c calls that look like this:
[NSString stringWithFormat:@"%@ %i%% %@", NSLocalizedString(@"Capacity1", @""), [[device objectForKey:kDeviceDesignPercent] intValue], NSLocalizedString(@"Capacity2", @"")]

This produces, a message that looks something like this:
"Maximum capacity is 92% of design capacity."

(But localized to the user's language, of course.)

My question is... is there some way I could write this so that I only have one entry in my strings file (Capacity) instead of two (Capacity1 and Capacity2).

I'm thinking such a call might look something like:
[NSString stringWithFormat:@"%@", NSLocalizedString(@"Capacity", @""), [[device objectForKey:kDeviceDesignPercent] intValue]

And then inside of my strings file, I could include the %i. Why?

I feel like the code would look simpler and I'd have to explain less to my translator. Oh, it would also make modifying the message so that if I decide to change how many variables are in it easier.

So, any help would be greatly appreciated. Thanks!



lee1210
May 5, 2012, 11:02 PM
https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/LoadingResources/Strings/Strings.html

Formatting String Resources

That page shows an example, including reordering. Note that your format string itself would be localized, your example would not use the int variable.

-Lee

ArtOfWarfare
May 6, 2012, 07:10 AM
Excellent!

I almost didn't post the question because I didn't think it was actually possible! Now I'm glad I did. :)

Thanks for that answer.

For those wondering, I have changed my code to this:
[NSString stringWithFormat:NSLocalizedString(@"Capacity %d%%", @""), [[device objectForKey:kDeviceDesignPercent] intValue]]

And my strings file to this:
"Capacity %d%%" = "Max capacity is %d%% of designed capacity.";