Pass by Reference

Discussion in 'Mac Programming' started by zcarter, Mar 23, 2008.

  1. zcarter macrumors member

    Apr 21, 2007
    How do you pass by reference in OOC for the iPhone?

    For example, in C++ if I wanted to get the variable rows out of this function I would do something like this...

    (Very down to earth)

    void Function(int& rows)
    rows = 10;
  2. admanimal macrumors 68040

    Apr 22, 2005
    Well the first thing to keep in mind is that references in C++ are just pointers with some sugar on them that allow you to do stuff without dealing with pointer semantics. So if you want to achieve the effect of passing an argument by reference, you just have the argument be a pointer to whatever you want to alter.

    An example from an iPhone AppDelegate:

    - (void)applicationDidFinishLaunching: (UIApplication *)application

    application is effectively passed by reference in that whatever operations you do to application inside of this function will persist when it returns (i.e. you are operating on the original object not a copy of it).

    So your example would be:

    void Function(int* rows)
    *rows = 10;

    and when you call the function you would do it with Function(&x) where x is an int. Don't confuse the address-of operator (&) with the reference sign in C++, their use is somewhat different.

    If you are dealing with objects rather than primitives, you don't really need to worry about it since the normal way of doing things in Obj-C is to only use pointers to objects, so the natural way of coding in Obj-C already has the effect of passing objects by reference.
  3. lazydog macrumors 6502a

    Sep 3, 2005
    Cramlington, UK
    I do believe you can do this by using the Objective-C++ compiler. All you need to do is give your file a .mm extension.

    b e n
  4. zippyfly macrumors regular

    Mar 22, 2008

    I don't know C++ but for C and Objective-C you pass by reference using pointers.

    int *myPntr = &value;

    now myPntr contains the address where value holds its data.

    If you send myPntr to a function (or method) and the method modifies the underlying data when you resolve myPntr using *myPntr (the dereferencing operator) the data is permanently modified. It is not duplicated and limited to the variable scope of the method routine. So when it returns from the method, the data is already modified. You do not even have to return the value (and you can only return one value anyway). So probably you can just return the boolean TRUE for a mission accomplished.

    You can pass multiple such pointers to methods that take pointers as arguments. Note that ObjC can also take these as objects (which are actually just pointers, to be technical about it) and the object members (the values) will also be permanently modified by the method.

    (Caveat: I am just starting to learn Objective-C actually but I think the above is correct.)

Share This Page