Localizing Dynamic Plural Noun messages (e.g. “5 Items Processed”) on iPhone using Objective-C

后端 未结 4 1088
故里飘歌
故里飘歌 2020-12-22 23:50

In my current app, I have code that displays a message, e.g. \"5 Items Processed.\" To keep the phrase grammatically correct, i.e. whether or not it should be \"5 Item\" or

4条回答
  •  眼角桃花
    2020-12-23 00:27

    My team developed an open source library for handling just this situation, checkout our iOS i18n plural library on github.

    The basic premise is that the keys for plural strings are extended to contain their plural form according to the CLDR plural rules and the lookup of the strings does not use the typical NSLocalizedString.

    The English file for the example posted would look like this:

    "%d Items Processed##{one}"   = "1 Item Processed";    
    "%d Items Processed##{other}" = "%d Items Processed";
    

    The lookup would then be done using a SLPluralizedString function

    SLPluralizedString(@”%d Items Processed”, numItems, @”Number of items processed”);
    

    At runtime, for English the String "1 Item Processed" or "%d Items Processed" would be returned depending on the value of numItems.

    The Russian file would then look like this:

    "%d Items Processed##{one}"   = "%d элемент обработан";
    "%d Items Processed##{few}"   = "%d элемента обработано";
    "%d Items Processed##{many}"  = "%d элементов обработано";
    "%d Items Processed##{other}" = "%d элемента обработано";
    

    Your code then to lookup "Items Processed" for Russian or any other language wouldn't have to change and the library would return the correct String according to the CLDR plural rules for that particular language.

    Please feel free to share your thoughts on the library, suggestions, improvements, etc.

提交回复
热议问题