Format-Specifiers

suggest change

Introduction

Format specifiers are used in Objective-C to interpolate values into a string.

Syntax

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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents