tags:

views:

115

answers:

3

I want to make an method which takes an CGFloat by reference.

Could I do something like this?

- (void)doStuff:(CGFloat*)floatPointer

I guess this must look different than other object pointers which have two of those stars. Also I'm not sure if I must do something like:

- (void)doStuff:(const CGFloat*)floatPointer

And of course, no idea how to assign an CGFloat value to that floatPointer. Maybe &floatPointer = 5.0f; ?

Could someone give some examples and explain these? Would be great!

+2  A: 

If you are passing a CGFloat by reference, then accessing it is simple:

- (void)doStuff:(CGFloat*)floatPointer {
    *floatPointer = 5.0f;
}

Explanation: as you are getting a reference, you need to de-reference the pointer (with the *) to get or set the value.

Laurent Etiemble
That's good to know. Thanks. Why must I write the const keyword in front of CGFloat?
dontWatchMyProfile
You can't assign a value to a const pointer...
KennyTM
The const keyword says: "I pass you the reference to but you are not allowed to modify it".
Laurent Etiemble
I'm getting an error: assignment of read-only location
dontWatchMyProfile
Fix a typo in the code: remove the const modifier.
Laurent Etiemble
+2  A: 

objective-c is still c, so

-(void) doStuff (CGFloat *) f
{
  *f = 1.2;
}

call with

CGFloat f = 1.0;
[self doStuff:&f];
ohho
A: 

if you (hate pointers and ;-) prefer objective-c++ pass by reference, the following is an alternative:

-(void) doStuffPlusPlus:(CGFloat &) f
{
   f = 1.3;
}

call by

CGFloat abc = 1.0;
[self doStuffPlusPlus:abc];

and, you need to rename the source filename from ???.m to ???.mm

ohho