01.02.2014 Views

Objective-C Fundamentals

Objective-C Fundamentals

Objective-C Fundamentals

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Pointers and the difference between reference and value types<br />

59<br />

You may have noticed that the NSString example contained a * character before the<br />

variable name. This character has special significance (you’ll notice it’s also present in<br />

the declaration of the id data type discussed in the sidebar). This additional character<br />

indicates that the data type is a pointer. But what exactly does this mean?<br />

3.3 Pointers and the difference between reference and value types<br />

A variable in an application consists of four components:<br />

■<br />

■<br />

■<br />

■<br />

Name<br />

Location (where it’s stored in memory)<br />

Type (what kind of data it can store)<br />

Current value<br />

Until now, we haven’t covered where variables are located or whether they are accessible<br />

by means other than their names. Understanding these concepts is closely related<br />

to the concept of pointers.<br />

3.3.1 Memory maps<br />

You can consider the memory of the iPhone as being made up of a large pile of bytes,<br />

each stacked one on top of another. Each byte has a number associated with it, called<br />

an address, similar to houses having an associated street number. Figure 3.1 represents<br />

several bytes of the iPhone’s memory, starting at address 924 and extending through<br />

address 940.<br />

When you allocate a variable in your application, the compiler reserves an explicit<br />

amount of memory for it. For example, a statement such as int x = 45 causes the compiler<br />

to reserve 4 bytes of memory to store the current value of x. This is represented<br />

in figure 3.1 by the 4 bytes starting at address 928.<br />

3.3.2 Obtaining the address of a variable<br />

Referring to the name of a variable in an expression will access or update its current<br />

value. By placing the address-of (&) operator in front of a variable name, you can learn<br />

the address at which the variable is currently stored.<br />

A variable that can store the address of another variable is called a pointer because<br />

it’s said to “point to” the location of another value. The following code snippet demonstrates<br />

how you can use the address-of operator.<br />

int x = 45;<br />

int *y = &x;<br />

Figure 3.1 Representation of a region of the iPhone’s memory showing the location<br />

of variable x

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

Saved successfully!

Ooh no, something went wrong!