Format-Specifiers
suggest changeIntroduction
Format specifiers are used in Objective-C to interpolate values into a string.
Syntax
- %@ //String
- %d //Signed 32-bit integer
- %D //Signed 32-bit integer
- %u //Unsigned 32-bit integer
- %U //Unsigned 32-bit integer
- %x //Unsigned 32-bit integer in lowercase hexadecimal format
- %X //Unsigned 32-bit integer in UPPERCASE hexadecimal format
- %o //Unsigned 32-bit integer in octal format
- %O //Unsigned 32-bit integer in octal format
- %f //64-bit floating-point number
- %F //64-bit floating-point number printed in decimal notation
- %e //64-bit floating-point number in lowercase scientific notation format
- %E //64-bit floating-point number in UPPERCASE scientific notation format
- %g //special case %e which uses %f when less than 4 sig-figs are available, else %e
- %G //special case %E which uses %f when less than 4 sig-figs are available, else %E
- %c //8-bit unsigned character
- %C //16-bit UTF-16 code unit
- %s //UTF8 String
- %S //16-bit variant of %s
- %p // void pointer in lowercase hexadecimal, with a leading
0x - %zx //
size_tprinted in hexadecimal (zis the length modifier, not a variant of%p) - %a //64-bit floating-point number in scientific notation with leading ‘0x’ and one hexadecimal digit before the decimal point using a ‘p’ to notate the exponent.
- %A //64-bit floating-point number in scientific notation with leading ‘0x’ and one hexadecimal digit before the decimal point using an ‘P’ to notate the exponent.
Remarks
Due to the nature of format-specifiers, if you wish to include the percentage symbol (%) in your string, you must escape it using a second percentage symbol.
Example:
int progress = 45;//percent
NSString *progressString = [NSString stringWithFormat:@"Progress: %i%%", (int)progress];
NSLog(@"%@", progressString); // logs "Progress: 45%"
No Format Specifier for BOOL-type exists.
Common-use solutions include:
BOOL myBool = YES;
NSString *boolState = [NSString stringWithFormat:@"BOOL state: %@", myBool?@"true":@"false"];
NSLog(@"%@", boolState); // logs "BOOL state: true"
This uses a ternary to pick a string.
BOOL myBool = YES;
NSString *boolState = [NSString stringWithFormat:@"BOOL state: %d", myBool];
NSLog(@"%@", boolState); // logs "BOOL state: 1"
%d prints the integer value 1 or 0, not a binary bit string. BOOL is not always 0 or 1 if it is a signed char and some other value was stored in it.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents