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 />

61<br />

Arrays are pointers in disguise<br />

A variable identifier for a C-style array can at some level be thought of as a simple<br />

pointer. This pointer always points to the first element in the array. As an example,<br />

the following is perfectly valid <strong>Objective</strong>-C source code:<br />

int ages[50];<br />

int *p = ages;<br />

NSLog(@"Age of 10th person is %d", p[9]);<br />

Notice you can assign the array variable to a pointer variable directly without using<br />

the & operator, and you can use the familiar [] syntax to calculate an offset from the<br />

pointer. A statement such as p[9] is another way to express *(p + 9): it’s a shorthand<br />

way to say “add 9 to the pointer’s current value and then dereference it.”<br />

When working with pointers to structure-based data types, a special dereferencing syntax<br />

is available that allows you to deference the pointer and access a specific field in<br />

the structure in a single step, using the -> operator:<br />

struct box *p = ...;<br />

p->width = 20;<br />

The -> operator on the second line dereferences the pointer p and then accesses the<br />

width field in the structure. While following a pointer to read or alter the value it<br />

points at, it’s sometimes helpful to compare two pointers to check if they point to<br />

identical values.<br />

3.3.4 Comparing the values of pointers<br />

When comparing the values of two pointers, it’s important to ensure you’re performing<br />

the intended comparison. Consider the following code snippet:<br />

int data[2] = { 99, 99 };<br />

int *x = &data[0];<br />

int *y = &data[1];<br />

if (x == y) { NSLog(@"The two values are the same"); }<br />

You might expect this code to emit the message "The two values are the same" but it<br />

doesn’t. The statement x == y compares the address of each pointer, and because x<br />

and y both point to different elements in the data array, the statement returns NO.<br />

If you want to determine if the values pointed to by each pointer are identical, you<br />

dereference both pointers:<br />

if (*x == *y) { NSLog(@"The two values are the same"); }<br />

Now that you understand the concept of pointers and how multiple pointers can reference<br />

the same object, you’re ready to communicate with the object. Communicating<br />

with an object enables you to interrogate it for details it stores or to request that<br />

the object perform a specific task using the information and resources at its disposal.

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

Saved successfully!

Ooh no, something went wrong!