Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abstracting out Strings in objective-c (iPhone)

I am working on an iphone application and I am wondering what the correct practice is for abstracting out strings. I am used to creating a file with constant strings and referencing them in my application (such as urls, port numbers or even button labels). I am wondering if this is considered good practice in Obj-C and if so what the best way to do it is? Should I make a class with the strings? Or use the ".strings" file?

p.s I may be localizing my application at a later time. I havent looked into how to do it, but I figure abstracting out my strings is a good idea while i'm developping.

Thank you! MGA

like image 361
Matt GA Avatar asked May 10 '11 04:05

Matt GA


1 Answers

generally, you interface with NSBundle. You use a string to read a localized version of the string (which is loaded from a localized strings file).

there are also some macros some people use to lighten the syntax, these are prefixed with NSLocalizedString. NSLocalizedString implementations use NSBundle.

imo, you should use string constants to identify the localized string you read (like you should with dictionaries and object keys).

you can declare your constants using this form (objc assumed):

extern NSString* const MONAppString_Download;

and define like so:

NSString* const MONAppString_Download = @"Download";

then access it using:

NSString * tableName = nil; // << using the default
NSString * localized =
  [[NSBundle mainBundle]
    localizedStringForKey:MONAppString_Download
     value:MONAppString_Download // << return the string using the default localization if not found
      table:tableName];

sometimes it helps to create wrapper functions to reduce the noise, especially when you use them in many places:

// @return what's set to the above variable named  'localized'.
NSString * MONLocalized_Download();

then you set up your strings files like a map, one for each localization you support.

so, whenever you need to read a string which is visible to the user, you use the above form. also consider that there are other resources to localize (nibs, images, pdfs, etc.) which you may bundle with your app. much of the work here is also abstracted by NSBundle, of CFBundle, if you prefer.

good luck

like image 91
justin Avatar answered Sep 28 '22 11:09

justin