JeremyF
JeremyF

Reputation: 745

Objective-C: What is %-2i in NSLog?

I am reading through a book on Objective-C and came by the following without any explanation:

NSLog(@"%-2i %i", n1, n2);

What does %-2i mean it just prints out the number the same way %i does?

Thank you.

Upvotes: 1

Views: 124

Answers (3)

Blitz
Blitz

Reputation: 5671

This type of question is usually frowned upon, as it's a simple thing to look up in the documentation, but let me add the relevant links:

Search for NSlog on google lets us to this page of the apple documentation: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Functions/Reference/reference.html

which tell us something about a "formatted string" and a @"format" (Saddly no direct link). But when you plug that into the search bar at the top, you eventually get to https://developer.apple.com/library/mac/documentation/CoreFoundation/Conceptual/CFStrings/formatSpecifiers.html. Again, it does not list the %i, but tells you to look at the IEEE fprintf documentation: http://pubs.opengroup.org/onlinepubs/009695399/functions/printf.html.

And there finally, you find both the definition of the %i and the -2i:

A negative field width is taken as a '-' flag followed by a positive field width. A negative precision is taken as if the precision were omitted

Upvotes: 1

stokastic
stokastic

Reputation: 128

I believe it left-aligns the first integer to 2 characters, a better answer is here:

objective-c code to right pad a NSString?

Upvotes: 1

trojanfoe
trojanfoe

Reputation: 122411

NSLog() and [NSString stringWithFormat:] use printf(3) formatting rules and from the printf manpage:

A negative field width flag; the converted value is to be left adjusted on the field boundary. Except for n conversions, the converted value is padded on the right with blanks, rather than on the left with blanks or zeros. A - overrides a 0 if both are given.

So it prints the integer using 2 spaces which are left-aligned.

Upvotes: 2

Related Questions