开发者

Abstracting out Strings in objective-c (iPhone)

开发者 https://www.devze.com 2023-03-03 21:39 出处:网络
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 t

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


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

0

精彩评论

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

关注公众号