34,333
edits
Changes
no edit summary
In the preceding chapters on object-oriented programming we have used, but not described , a feature of Objective-C (actually derived form the underlying C programming language) in the form of ''pointers'' and ''indirection''. A clear understanding of this topic is important when working with objects and also when passing values as arguments to methods and functions.
== How Variables are Stored ==
</pre>
When the above code is executed, a block of memory large enough to hold an integer value is reserved in memory and the value of 10 is placed at that location. When ever Whenever we reference this variable in code, we are actually using the variable value. For example, the following code adds the value of ''myvar'' (i.e. 10) to the constant value 20 to arrive at a result of 30.
<pre>
</pre>
Clearly, even though the value passed through to ''myFunction'' was increased by 20 the value of ''myvar'' remained unchanged. This is because what was passed through as an argument to ''myFunction'' was the ''value'' of ''myvar'', not the ''myvar'' variable itself. Therefore, in ''myFunction'' we were simply working on a constant value of 10 that had absolutely no connection to the origianl original ''myvar'' variable.
In order to be able to work on the actual variable in the function we need to use something called indirection.
Indirection involves working with pointers to the location of variables and objects rather than the contents of those items. In other words, instead of working with the ''value'' stored in a variable, we work with a ''pointer'' to the ''memory address'' where the variable is located.
Pointers a are declared by prefixing the name with an asterisk (*) character. For example to declare a pointer to our ''myvar'' variable we would write the following code:
<pre>
</pre>
We now have now implemented a level of indirection by creating a ''pointer'' to our variable. As such, we can now pass this pointer through as an argument to our function such that we wil will be able to work on the actual variable, rather than just the value (10) of the variable. In order to access the value of a variable using a pointer to that variable, we prefix the pointer variable name with an asterisk (*). When we do this we are telling the compiler we want to work with the contents of the variable or object at the memory address contained within the pointer:
<pre>
== Indirection and Object Copying ==
<pre>