Have you read through the entire chapter? The last section "How Things Work" explains the relationship between pointers and objects.
First of all, why even use a pointer? Why not just use the variable instead?
You would use pointer mainly for indirection. This is a very efficient way to deal with data.
With indirection you are saying "do something with the data located at this memory address".
Without it you would need to supply the data directly (i.e. copy). This may not sound like a big deal until you consider the difference between working with megabytes of data at memory location x or copying over megabytes of data and then working with it.Edit:
Also, pointers are really the only way you can deal with data of varying size. A perfect example is a string. A standard C-string is just a bunch of characters stored in memory and terminated by a NULL character.
If you want to pass a string to a method, the only way to do it is by using a pointer to the string. Otherwise you would need a different method for each possible size of string that could be passed as an argument.
So why use a pointer for a variable that is only an int, float, char, etc... ?
When a variable is passed as an argument for a method, only the variable's value is passed. The method is essentially working on a copy of the variable.
If you pass a pointer to a variable it is the memory address the variable is stored at that the method receives. This way any modification the method does to the variable's value will be done on the original variable and not a copy.
Also I'm thinking *ptr is more of a getter and &ptr is more of a setter, is that correct?
Think of '&' as the address o
When declaring a variable '*' means a pointer to
When used to 'dereference' a pointer '*' means the value at the address pointed to by
int intValue; // an integer
int anotherValue; // another integer
int *intPtr; // Read it from right to left. 'intPtr' is a pointer to an 'int'
intPtr = &intValue // Make intPtr point to 'the address of' intValue.
*intPtr = 10; // set the 'value at the address pointed to by' intPtr to 10. This would be the same as intValue = 10;
anotherValue = *ptr; // make anotherValue equal to the 'value at the address pointed to by' intPtr.
// This would be the same as anotherValue = intValue;
To illustrate the point...
@interface MyClass : NSObject
*valuePtr += 10;
NSLog(@"*valuePtr + 10 = %i", *valuePtr);
value += 10;
NSLog(@"value + 10 = %i", value);
int main (int argc, const char * argv)
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
intValue = 5;
intPtr = &intValue;
NSLog(@"intValue before modifyInt = %i", intValue);
NSLog(@"intValue after modifyInt = %i\n\n", intValue);
NSLog(@"intValue before indirectModifyInt = %i", intValue);
NSLog(@"intValue after indirectModifyInt = %i\n\n", intValue);
NSLog(@"*intPtr before indirectModifyInt = %i", *intPtr);
NSLog(@"*inPtr after indirectModifyInt = %i", *intPtr);