Pointers in Objective-C
Objective-C is a strict superset of C. That means every feature of C is alive and kicking in Objective-C, pointers included. Five years of pointer free programming has made me…rusty. As the saying goes, “There is no better way to learn than to teach”.
1 2 3 4 5 6 7 8 9 10
This is your standard pointer example. int *b is an integer pointer that we are assigning the address of int a. The asterisk * is generally called the dereferencing or indirection operator and means “Give me the value stored at the address this pointer points to”. The & operator means “Give me the address in memory that this variable is stored at”.
What can often be confusing is that with one line declaration and initialization short-hand, the asterisk is not performing any dereferencing but is actually simply declaring that this is an integer pointer.
1 2 3 4 5 6
This snippet of code illustrates how this actually works in memory.
1 2 3 4 5
<em>0x7fff5fbff88c -> 2 0x7fff5fbff880 -> 0x7fff5fbff88c</em>
left number: the variables location in memory. right number: the value it stores.
Remember a pointer is like any other variable, it has its own location in memory but its value is simply another memory address. So when you write “*b” you are saying “Give me the value (2) stored at the address (0x7fff5fbff88c).
Pointers to Pointers
With pointers to pointers things get a little more complicated. A pointer can actually point to another pointer. Take the following code.
1 2 3 4 5 6 7
<em>0x7fff5fbff88c -> 2 0x7fff5fbff880 -> 0x7fff5fbff88c 0x7fff5fbff878 -> 0x7fff5fbff880</em>
int **c points to int *b which in turn points to int a. To further illustrate the following examples show how we can reference the same thing in multiple ways.
a == b == **c; //The value 2 &a; == b == c; //The address of a or 0x7fff5fbff88c
Pointers to pointers have practical uses in Objective-C when a method actually needs to return multiple values.
1 2 3 4
printNumber in this case can return a BOOL with the standard return statement and an optional error by setting our *anyError pointer to a new NSError object.
For example a sample implementation of printNumber:
1 2 3 4 5 6 7 8 9 10 11 12 13 14