Changes

Jump to: navigation, search

Pointers and Indirection in Objective-C

890 bytes added, 16:05, 13 November 2009
Indirection and Objects
The first line of code (BankAccount *account1;) is actually declaring that the variable named ''account1'' is a ''pointer to an object of type BankAccount''. We are, therefore, using indirection to provide a handle to our object. The calls to the alloc and init methods subsequently create the object in memory and the assign the address of that object to the account1 pointer variable. We are, therefore, using indirection once again.
 
One key point to note is that we do not need to prefix the object pointer with a * when perform operations such as calling methods. For example, we can call a method on our ''account1'' object without using an asterisk:
 
<tt>[account1 displayAccountInfo];</tt>
 
== Indirection and Object Copying ==
 
The fact that our references to object utilize indirection it is important to understand that when we use the assignment operator (=) to assign one object to another we are not actually creating a copy of the object. Instead, we are creating a second pointer to the same object:
 
<pre>
BankAccount *account1;
BankAccount *account2;
 
BankAccount *account1 = [[BankAccount alloc] init];
 
account2 = account1;
</pre>
 
In the above example, we will end up with two pointers (account1 and account2) that point to the same location in memory. We have not, therefore, created a copy of account1.

Navigation menu