01.02.2014 Views

Objective-C Fundamentals

Objective-C Fundamentals

Objective-C Fundamentals

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

42 CHAPTER 2 Data types, variables, and constants<br />

Portability is never as simple as it first seems<br />

If you followed our previous advice and made use of data types such as NSInteger<br />

and NSUInteger, you must be extra careful when using functions, such as NSLog,<br />

which accept format specifiers. On 32-bit targets, such as the iPhone, it’s common<br />

to use the %d specifier to format integer values, as demonstrated in the following<br />

code sample:<br />

NSInteger i = 45;<br />

NSLog(@"My value is %d", i);<br />

If you reuse this code in a 64-bit-based desktop application, however, it could result<br />

in incorrect behavior. In a 64-bit environment, a variable declared of type int stays<br />

at 32 bits in size, whereas a variable declared of type NSInteger is redefined to be<br />

equivalent to long, which makes it now 64 bits in size. Hence, the correct format<br />

specifier for NSInteger in a 64-bit environment is %ld:<br />

NSLog(@"My value is %ld", i);<br />

To avoid altering source code like this, Apple’s 64-bit Transition Guide for Cocoa recommends<br />

always casting such values to long or unsigned long (as appropriate).<br />

For example:<br />

NSLog(@"My value is %ld", (long)i);<br />

The typecast to long ensures that NSLog is always provided a 64-bit argument even<br />

if the current platform is 32 bit. This means %ld will always be the correct specifier.<br />

To further control the presentation of values, you can place a number between the %<br />

and the field data type. This acts as a minimum field width and will right-align the value<br />

by padding out the string with spaces if it’s not already long enough. For example:<br />

int a = 92;<br />

int b = 145;<br />

NSLog(@"Numbers:\nA: %6d\nB: %6d", a, b);<br />

This should result in the console window displaying output similar to the following:<br />

Numbers:<br />

A: 92<br />

B: 145<br />

Placing a negative sign in front of the number causes NSLog to instead left-align the<br />

field, whereas prefixing the number with a zero pads with zeros instead of spaces.<br />

When formatting floating-point numbers, it’s also possible to specify the desired number<br />

of decimal places by preceding the minimum field-width specifier with a decimal<br />

point and the desired number of decimal places. As an example, the following code<br />

snippet emits the string "Current temperature is 40.54 Fahrenheit":<br />

float temp = 40.53914;<br />

NSLog(@"Current temperature is %0.2f Fahrenheit", temp);

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!