
The following example shows how to pass CGPoint by reference in Objective-C.
Class Interface
@interface
-(void)multiplyX:(CGPoint *)point by:(float)a
@end
Class Implementation
@implementation
-(void)multiplyX:(CGPoint *)point by:(float)a {
(*point).x = (*point).x * a;
}
@end
Calling This Type of Method
In order to call this method, you would simply do the following.
CGPoint pointA = CGPointMake(20.0f, 10.0f);
float aFloatValue = 10.0f;
[self multiplyX:&pointA by:aFloatValue];
Did You Notice The &
Do you notice anything different about the above method call?
You should have noticed the & character before the &pointA variable. This tells the method that it should pass pointA by reference.
CGPoint As A Pointer
A pointer is simply a reference to a location in memory. So, when we declared a method call to change CGPoint by reference, we needed to pass CGPoint as a pointer. We did this above like so, (CGPoint*)point.
Using the Pointer To CGPoint Within The Method
In orde to access the contents of CGPoint, we need to put parenthesis star around the variable name. (*point).x or (*point).y. Also, when assigning a new value to the struct we need to do this (*point) = CGPointMake(20,20);.
You Only Access The Pointers Memory Location
The parenthesis are needed to ensure that we are accessing the pointers memory location and not the memory location of the variables within the CGPoint.
If you do not include the parenthesis, the compiler will give you a bunch of errors and your code will not compile.
Second Example
Lets look at one last example.
This method will square the CGPoint argument and the changed value of p will be p squared.
-(void) method2:(CGPoint*)p {
CGPoint newPoint = (*p);
(*p).x = newPoint.x * newPoint.x;
(*p).y = newPoint.y * newPoint.y;
}
Calling the above method
CGPoint point = CGPointMake(10,10);
[self method2:&point];
The new changed value of point will be (100,100).
Conclusion
You have just upgraded your programming arsenal!
As you will see this seems complicated at first, but once you work through a couple examples on your own, you’ll be passing by reference frequently.
Passing by reference is a very handy tool and something all good programmers should know. Do not let the Objective-C syntax deter you from using this powerful tool.
If you are new to programming and still confused about pointers in Objective-C then please browse the web and apple’s developer documentation to brush up on this very fundamental programming topic.
The examples above are analogous to all other C structs.
I hope this helps everyone who is having problems with passing CGPoint by reference.


