Note that there are some explanatory texts on larger screens.

plurals
  1. POIs there a way to specify argument position/index in NSString stringWithFormat?
    primarykey
    data
    text
    <p>C# has syntax that allows you to specify the argument index in a string format specifier, e.g.:</p> <pre><code>string message = string.Format("Hello, {0}. You are {1} years old. How does it feel to be {1}?", name, age); </code></pre> <p>You can use arguments more than once and also omit arguments that are provided from being used. <a href="https://stackoverflow.com/questions/462580/string-format-for-c">Another question</a> mentions the same formatting for C/C++ in the form of <code>%[index]$[format]</code>, e.g. <code>%1$i</code>. I have not been able to get NSString to <strong>fully</strong> respect this syntax, because it does behave well when <em>omitting arguments</em> from the format. The following does not work as expected (EXC_BAD_ACCESS because it attempts to dereference the <code>age</code> parameter as a NSObject*):</p> <pre><code>int age = 23; NSString * name = @"Joe"; NSString * message = [NSString stringWithFormat:@"Age: %2$i", name, age]; </code></pre> <p>The positional arguments are respected only if there are no missing arguments from the format (which seems to be an odd requirement):</p> <pre><code>NSString * message = [NSString stringWithFormat:@"Age: %2$i; Name: %1$@", name, age]; </code></pre> <p>All these calls work properly in OS X:</p> <pre><code>printf("Age: %2$i", [name UTF8String], age); printf("Age: %2$i %1$s", [name UTF8String], age); </code></pre> <p>Is there a way of accomplishing this using NSString in Objective-C / Cocoa? It would be useful for localization purposes.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload