NSString stringWithFormat swizzled to allow missing format numbered args

后端 未结 2 1301
慢半拍i
慢半拍i 2020-12-12 03:45

Based on this SO question asked a few hours ago, I have decided to implement a swizzled method that will allow me to take a formatted NSString as the format arg

相关标签:
2条回答
  • 2020-12-12 04:28

    Whoa there!

    Instead of screwing with a core method that you very probably will introduce subtle bugs into, instead just turn on "Static Analyzer" in your project options, and it will run every build - if you get the arguments wrong it will issue a compiler warning for you.

    I appreciate your desire to make the application more robust but I think it very likely that re-writing this method will more likely break your application than save it.

    0 讨论(0)
  • 2020-12-12 04:40

    How about defining your own interim method instead of using format specifiers and stringWithFormat:? For example, you could define your own method replaceIndexPoints: to look for ($1) instead of %1$@. You would then format your string and insert translated replacements independently. This method could also take an array of strings, with NSNull or empty strings at the indexes that don't exist in the “untranslated” string.

    Your method could look like this (if it were a category method for NSMutableString):

    - (void) replaceIndexPointsWithStrings:(NSArray *) replacements
    {
        // 1. look for largest index in "self".
        // 2. loop from the beginning to the largest index, replacing each
        //    index with corresponding string from replacements array.
    }
    

    Here's a few issues that I see with your current implementation (at a glance):

    1. The __VA_ARGS__ thingy explained in the comments.
    2. When you use while (arg = va_arg(args, id)), you are assuming that the arguments are nil terminated (such as for arrayWithObjects:), but with stringWithFormat: this is not a requirement.
    3. I don't think you're required to escape the $ and @ in your string format in your arg-loop.
    4. I'm not sure this would work well if uaStringWithFormat: was passed something larger than a pointer (i.e. long long if pointers are 32-bit). This may only be an issue if your translations also require inserting unlocalised numbers of long long magnitude.
    0 讨论(0)
提交回复
热议问题