Search code examples
objective-cxcodestringwithformat

What does stringWithFormat:@"%@-1" mean?


I'm reading someone elses code and they are using %@-1 to format an integer. I can't find anything on Google since it ignores symbols. Anyone else had more experience at string formatting than me?

[NSString stringWithFormat:@"%@-1", subnumber]

Thanks!


Solution

  • According to the specification:

    Each conversion specification is introduced by the '%' character, or by the character sequence "%n$", after which the following appear in sequence:

    • Zero or more flags (in any order), which modify the meaning of the conversion specification.

    • An optional minimum field width. If the converted value has fewer bytes than the field width, it shall be padded with spaces by default on the left; it shall be padded on the right if the left-adjustment flag ( '-' ), described below, is given to the field width. The field width takes the form of an asterisk ( '*' ), described below, or a decimal integer.

    • An optional precision that gives the minimum number of digits to appear for the d, i, o, u, x, and X conversion specifiers; the number of digits to appear after the radix character for the a, A, e, E, f, and F conversion specifiers; the maximum number of significant digits for the g and G conversion specifiers; or the maximum number of bytes to be printed from a string in the s [XSI] [Option Start] and S [Option End] conversion specifiers. The precision takes the form of a period ( '.' ) followed either by an asterisk ( '*' ), described below, or an optional decimal digit string, where a null digit string is treated as zero. If a precision appears with any other conversion specifier, the behavior is undefined.

    • An optional length modifier that specifies the size of the argument.

    • A conversion specifier character that indicates the type of conversion to be applied.

    We're using a conversion of the first type, since there's no dollar sign in here. Note the words in sequence at the top of the above list. The @ is a conversion specifier character (as mentioned here), which indicates that we should access the value passed in as an NSObject and read its description property. Since we've already reached the last bullet point, the format code actually ends after the @ symbol, and as @Kevin Ballard pointed out, the -1 is parsed as literal text.