views:

389

answers:

3

Hi, I'm trying to pass a nsstring by reference but it doesn't work.

this is the function:

+(void)fileName:(NSString *) file
{
    file = @"folder_b";
}

and this is the call:

NSString *file;

[function fileName:file];

nslog(@"%@",file);    // and there is nothing in the string....

What I must do to pass my string byref.

A: 

I suspect this is because NSString is immutable. Have you tried NSMutableString?

Jason
Using a mutable string cannot 'set' the variable to a new object, so strictly will not work in the example given. But depending on the circumstances it is likely the best way to go (+1) (instead of double object ptr's)
Akusete
One option would be to pass an `NSMutableString` and then use `setString:`, but that wouldn't be "by reference".
andyvn22
@andyvn: You are right, my point was that (as often is the case) the technically write answer to the question, and the best solution a the problem are not the same thing.
Akusete
There's no reason to be passing by reference to this kind of method at all.
Preston
+6  A: 

I believe you're looking for:

+ (void)fileName:(NSString **)file
{
  *file = @"folder_b";
}

What's really done here is we're working with a pointer to a pointer to an object. Check C (yup, just plain C) guides for "pointer dereference" for further info.

(...But as has been pointed out repeatedly, you're asking the wrong question.)

andyvn22
Thomas Müller
Why the heck would you ever declare a method that has a single pass-by-reference argument **and** a `(void)` return?!??!
bbum
@bbum: The parameter *might* be an in/out parameter, but even then . . .
dreamlax
@andyvn22 This answer would make the code work, but it is not the correct answer, because passing by reference to this method is completely pointless. See bbum's answer.
Preston
+31  A: 

If you have want to return a value, then return a value. Pass by reference in Cocoa/iOS is largely limited to NSError**.

Given:

+(void)fileName:(NSString *) file

Then do:

+(NSString *) fileName;

And be done with it.

If you need to return more than one value at a time, that begs for a structure or, more often, a class.

In Objective-C, pass by reference smells like you are doing it wrong.

bbum